diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index cf1c0bfefa1..634ba51b9bd 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -7,5 +7,5 @@ - [ ] Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community. - [ ] If contributing template-only or documentation-only changes which will change sample output, [build the project](https://github.com/OpenAPITools/openapi-generator#14---build-projects) beforehand. - [ ] Run the shell script `./bin/generate-samples.sh`to update all Petstore samples related to your fix. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/configs/java*`. For Windows users, please run the script in [Git BASH](https://gitforwindows.org/). -- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master` +- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `5.1.x`, `6.0.x` - [ ] Copy the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) to review the pull request if your PR is targeting a particular programming language. diff --git a/.gitignore b/.gitignore index 26c01a81696..ebe0dc1ff9c 100644 --- a/.gitignore +++ b/.gitignore @@ -258,3 +258,6 @@ samples/client/petstore/c/*.so # Ruby samples/openapi3/client/petstore/ruby/Gemfile.lock samples/openapi3/client/petstore/ruby-faraday/Gemfile.lock + +# Crystal +samples/client/petstore/crystal/lib diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000000..b901097f2db --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar index f775b1c04cf..2cc7d4a55c0 100755 Binary files a/.mvn/wrapper/maven-wrapper.jar and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index eb91947648c..642d572ce90 100755 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1 +1,2 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/.travis.yml b/.travis.yml index 52ad4a03ce7..edbd8c27dd5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -62,6 +62,17 @@ addons: - petstore.swagger.io before_install: + # to run petstore server locally via docker + - echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin || true + - docker pull swaggerapi/petstore + - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore + - docker ps -a + # install crystal + - curl -sSL https://dist.crystal-lang.org/apt/setup.sh | sudo bash + - curl -sL "https://keybase.io/crystal/pgp_keys.asc" | sudo apt-key add - + - echo "deb https://dist.crystal-lang.org/apt crystal main" | sudo tee /etc/apt/sources.list.d/crystal.list + - sudo apt-get update + - sudo apt install crystal - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.22.0 - export PATH="$HOME/.yarn/bin:$PATH" # install rust @@ -75,10 +86,6 @@ before_install: - npm config set registry http://registry.npmjs.org/ # set python 3.6.3 as default - source ~/virtualenv/python3.6/bin/activate - # to run petstore server locally via docker - - docker pull swaggerapi/petstore - - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - - docker ps -a # -- skip bash test to shorten build time # Add bats test framework and cURL for Bash script integration tests #- sudo add-apt-repository ppa:duggan/bats --yes @@ -124,7 +131,7 @@ before_install: fi; - pushd .; cd website; yarn install; popd # install Deno - - sh -s v1.1.2 < ./CI/deno_install.sh + - sh -s v1.6.2 < ./CI/deno_install.sh - export PATH="$HOME/.deno/bin:$PATH" install: diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index 70b541743d8..25705a08528 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -41,13 +41,14 @@ elif [ "$NODE_INDEX" = "2" ]; then curl -sSL https://get.haskellstack.org/ | sh stack upgrade stack --version - # install r + # prepare r sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu trusty/" >> /etc/apt/sources.list' gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9 gpg -a --export E084DAB9 | sudo apt-key add - sudo apt-get update sudo apt-get -y install r-base R --version + # install curl sudo apt-get -y build-dep libcurl4-gnutls-dev sudo apt-get -y install libcurl4-gnutls-dev diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9644a5cb366..30258ec9fd6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,6 +49,7 @@ Code change should conform to the programming style guide of the respective lang - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style - Clojure: https://github.com/bbatsov/clojure-style-guide +- Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style - Elixir: https://github.com/christopheradams/elixir_style_guide - Eiffel: https://www.eiffel.org/doc/eiffel/Coding%20Standards diff --git a/README.md b/README.md index 48e5a79fdb2..7ea36a530a8 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.0.0`): +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.0.1`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator) @@ -18,6 +18,22 @@ [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/master?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/openapitools/openapi-generator/Check%20Supported%20Java%20Versions/master?label=Check%20Supported%20Java%20Versions&logo=github&logoColor=green)](https://github.com/OpenAPITools/openapi-generator/actions?query=workflow%3A%22Check+Supported+Java+Versions%22) +[5.1.x](https://github.com/OpenAPITools/openapi-generator/tree/5.1.x) (`5.1.x`): +[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.1.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) +[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.1.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) +[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.1.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.1.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) +[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.1.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) +[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/5.1.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) + +[6.0.x](https://github.com/OpenAPITools/openapi-generator/tree/6.0.x) (`6.0.x`): +[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) +[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/6.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) +[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=6.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=6.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) +[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/6.0.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) +[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/6.0.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) +
@@ -60,11 +76,11 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) | +| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) | | **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | | **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc** | | **Configuration files** | [**Apache2**](https://httpd.apache.org/) | -| **Others** | **GraphQL**, **JMeter**, **MySQL Schema**, **Protocol Buffer** | +| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer** | ## Table of contents @@ -102,7 +118,9 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | -| 5.0.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.1-SNAPSHOT/) | TBD | Patch release with enhancements, bug fixes, etc | +| 6.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.0.0-SNAPSHOT/) | Nov/Dec 2021 | Minor release with breaking changes (no fallback) | +| 5.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.1.0-SNAPSHOT/) | Mar/Apr 2021 | Minor release with breaking changes (with fallback) | +| 5.0.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.1-SNAPSHOT/) | Jan/Feb 2021 | Patch release with enhancements, bug fixes, etc | | [5.0.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0) (latest stable release) | 21.12.2020 | Major release with breaking changes (no fallback) | | [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) | @@ -824,6 +842,7 @@ Here is a list of template creators: * C# (.NET Standard 1.3 ): @Gronsak * C# (.NET 4.5 refactored): @jimschubert [:heart:](https://www.patreon.com/jimschubert) * Clojure: @xhh + * Crystal: @wing328 * Dart: @yissachar * Dart (refactor): @joernahrens * Dart 2: @swipesight @@ -939,6 +958,7 @@ Here is a list of template creators: * Schema * Avro: @sgadouar * GraphQL: @wing328 [:heart:](https://www.patreon.com/wing328) + * Ktorm: @Luiz-Monad * MySQL: @ybelenko * Protocol Buffer: @wing328 @@ -990,11 +1010,11 @@ If you want to join the committee, please kindly apply by sending an email to te | Elm | @eriktim (2018/09) | | Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) | | F# | @nmfisher (2019/05) | -| Go | @antihax (2017/11) @grokify (2018/07) @kemokemo (2018/09) @bkabrda (2019/07) | +| Go | @antihax (2017/11) @grokify (2018/07) @kemokemo (2018/09) @jirikuncar (2021/01) | | GraphQL | @renepardon (2018/12) | | Groovy | | | Haskell | | -| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @bkabrda (2020/01) | +| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @nmuesch (2021/01) | | Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) @andrewemery (2019/10) @4brunu (2019/11) @yutaka0m (2020/03) | | Lua | @daurnimator (2017/08) | | Nim | | diff --git a/bin/configs/crystal.yaml b/bin/configs/crystal.yaml new file mode 100644 index 00000000000..74badcce662 --- /dev/null +++ b/bin/configs/crystal.yaml @@ -0,0 +1,9 @@ +generatorName: crystal +outputDir: samples/client/petstore/crystal +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/crystal +additionalProperties: + shardVersion: 1.0.0 + moduleName: Petstore + shardName: petstore +strictSpecBehavior: false diff --git a/bin/configs/ktorm-schema.yaml b/bin/configs/ktorm-schema.yaml new file mode 100644 index 00000000000..aff895cb279 --- /dev/null +++ b/bin/configs/ktorm-schema.yaml @@ -0,0 +1,7 @@ +generatorName: ktorm-schema +outputDir: samples/schema/petstore/ktorm +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/ktorm-schema +additionalProperties: + hideGenerationTimestamp: true + importModelPackageName: org.openapitools.client.models \ No newline at end of file diff --git a/bin/configs/ruby-extensions-x-auth-id-alias.yaml b/bin/configs/ruby-extensions-x-auth-id-alias.yaml new file mode 100644 index 00000000000..7f51216567c --- /dev/null +++ b/bin/configs/ruby-extensions-x-auth-id-alias.yaml @@ -0,0 +1,8 @@ +generatorName: ruby +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/ruby-client +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +templateDir: modules/openapi-generator/src/main/resources/ruby-client +additionalProperties: + gemName: x_auth_id_alias + gemVersion: 1.0.0 + moduleName: XAuthIDAlias \ No newline at end of file diff --git a/bin/configs/typescript-angular-v9-provided-in-any.yaml b/bin/configs/typescript-angular-v9-provided-in-any.yaml new file mode 100644 index 00000000000..6678f7bb2ec --- /dev/null +++ b/bin/configs/typescript-angular-v9-provided-in-any.yaml @@ -0,0 +1,6 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +additionalProperties: + ngVersion: 9.0.0 + providedIn: any diff --git a/docs/contributing.md b/docs/contributing.md index 482ffecf4dd..a791b0d6f1b 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -53,6 +53,7 @@ Code change should conform to the programming style guide of the respective lang - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style - Clojure: https://github.com/bbatsov/clojure-style-guide +- Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style - Elixir: https://github.com/christopheradams/elixir_style_guide - Eiffel: https://www.eiffel.org/doc/eiffel/Coding%20Standards diff --git a/docs/generators.md b/docs/generators.md index 8a68e529532..739d0cfd19a 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -16,6 +16,7 @@ The following generators are available: * [cpp-restsdk](generators/cpp-restsdk.md) * [cpp-tizen](generators/cpp-tizen.md) * [cpp-ue4 (beta)](generators/cpp-ue4.md) +* [crystal (beta)](generators/crystal.md) * [csharp](generators/csharp.md) * [csharp-dotnet2 (deprecated)](generators/csharp-dotnet2.md) * [csharp-netcore](generators/csharp-netcore.md) @@ -141,6 +142,7 @@ The following generators are available: ## SCHEMA generators * [avro-schema (beta)](generators/avro-schema.md) * [graphql-schema](generators/graphql-schema.md) +* [ktorm-schema (beta)](generators/ktorm-schema.md) * [mysql-schema](generators/mysql-schema.md) * [protobuf-schema (beta)](generators/protobuf-schema.md) diff --git a/docs/generators/c.md b/docs/generators/c.md index 29df6b2096e..448cf98b4bf 100644 --- a/docs/generators/c.md +++ b/docs/generators/c.md @@ -56,41 +56,109 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • _noreturn
  • _static_assert
  • _thread_local
  • +
  • alignas
  • +
  • alignof
  • +
  • and
  • +
  • and_eq
  • +
  • asm
  • +
  • atomic_cancel
  • +
  • atomic_commit
  • +
  • atomic_noexcept
  • auto
  • +
  • bitand
  • +
  • bitor
  • +
  • bool
  • break
  • case
  • +
  • catch
  • char
  • +
  • char16_t
  • +
  • char32_t
  • +
  • char8_t
  • +
  • class
  • +
  • co_await
  • +
  • co_return
  • +
  • co_yield
  • +
  • compl
  • +
  • concept
  • const
  • +
  • const_cast
  • +
  • consteval
  • +
  • constexpr
  • +
  • constinit
  • continue
  • +
  • decltype
  • default
  • +
  • delete
  • do
  • double
  • +
  • dynamic_cast
  • else
  • enum
  • +
  • explicit
  • +
  • export
  • extern
  • +
  • false
  • +
  • final
  • float
  • for
  • +
  • friend
  • goto
  • if
  • inline
  • int
  • long
  • +
  • mutable
  • +
  • namespace
  • +
  • new
  • +
  • noexcept
  • +
  • not
  • +
  • not_eq
  • +
  • nullptr
  • +
  • operator
  • +
  • or
  • +
  • or_eq
  • +
  • override
  • +
  • private
  • +
  • protected
  • +
  • public
  • +
  • reflexpr
  • register
  • +
  • reinterpret_cast
  • remove
  • +
  • requires
  • restrict
  • return
  • short
  • signed
  • sizeof
  • static
  • +
  • static_assert
  • +
  • static_cast
  • struct
  • switch
  • +
  • synchronized
  • +
  • template
  • +
  • this
  • +
  • thread_local
  • +
  • throw
  • +
  • transaction_safe
  • +
  • transaction_safe_dynamic
  • +
  • true
  • +
  • try
  • typedef
  • +
  • typeid
  • +
  • typename
  • union
  • unsigned
  • +
  • using
  • +
  • virtual
  • void
  • volatile
  • +
  • wchar_t
  • while
  • +
  • xor
  • +
  • xor_eq
  • ## FEATURE SET diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md new file mode 100644 index 00000000000..8965a800fff --- /dev/null +++ b/docs/generators/crystal.md @@ -0,0 +1,226 @@ +--- +title: Config Options for crystal +sidebar_label: crystal +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|legacyDiscriminatorBehavior|Set to true for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
    **true**
    The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
    **false**
    The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
    |true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|shardAuthor|shard author (only one is supported).| |null| +|shardAuthorEmail|shard author email (only one is supported).| |null| +|shardDescription|shard description.| |This shard maps to a REST API| +|shardHomepage|shard homepage.| |http://org.openapitools| +|shardLicense|shard license.| |unlicense| +|shardName|shard name (e.g. twitter_client| |openapi_client| +|shardVersion|shard version.| |1.0.0| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|Array| +|map|Hash| +|set|Set| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✓|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/ktorm-schema.md b/docs/generators/ktorm-schema.md new file mode 100644 index 00000000000..4f65a1ecc81 --- /dev/null +++ b/docs/generators/ktorm-schema.md @@ -0,0 +1,355 @@ +--- +title: Config Options for ktorm-schema +sidebar_label: ktorm-schema +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|addSurrogateKey|Adds the surrogate key for all models that don't already have a primary key (named by the above convention)| |false| +|artifactId|Generated artifact id (name of jar).| |ktorm| +|artifactVersion|Generated artifact's package version.| |1.0.0| +|defaultDatabaseName|Default database name for all queries| |sqlite.db| +|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| +|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| +|identifierNamingConvention|Naming convention of Ktorm identifiers(table names and column names). This is not related to database name which is defined by defaultDatabaseName option|
    **original**
    Do not transform original names
    **snake_case**
    Use snake_case names
    |original| +|importModelPackageName|Package name of the imported models| |org.openapitools.database.models| +|modelMutable|Create mutable models| |false| +|packageName|Generated artifact package name.| |org.openapitools.database| +|primaryKeyConvention|Primary key naming convention| |id| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sourceFolder|source folder for generated code| |src/main/kotlin| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|BigDecimal|java.math.BigDecimal| +|Date|java.util.Date| +|DateTime|java.time.LocalDateTime| +|File|java.io.File| +|LocalDate|java.time.LocalDate| +|LocalDateTime|java.time.LocalDateTime| +|LocalTime|java.time.LocalTime| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|kotlin.collections.ArrayList| +|list|kotlin.collections.ArrayList| +|map|kotlin.collections.HashMap| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✗|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/powershell.md b/docs/generators/powershell.md index 18cb16912c3..19ee0fe1218 100644 --- a/docs/generators/powershell.md +++ b/docs/generators/powershell.md @@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |powershellGalleryUrl|URL to the module in PowerShell Gallery (e.g. https://www.powershellgallery.com/packages/PSTwitter/).| |null| |projectUri|A URL to the main website for this project| |null| |releaseNotes|Release notes of the generated PowerShell module| |null| +|skipVerbParsing|Set skipVerbParsing to not try get powershell verbs of operation names| |null| |tags|Tags applied to the generated PowerShell module. These help with module discovery in online galleries| |null| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |null| diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index adb04b56dfd..bd90759d0fa 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -25,7 +25,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| -|providedInRoot|Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).| |false| +|providedIn|Use this property to provide Injectables in wanted level (it is only valid in angular version greater or equal to 9.0.0).|
    **root**
    The application-level injector in most apps.
    **none**
    No providedIn (same as providedInRoot=false)
    **any**
    Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.
    **platform**
    A special singleton platform injector shared by all applications on the page.
    |root| +|providedInRoot|Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0). IMPORTANT: Deprecated for angular version greater or equal to 9.0.0, use **providedIn** instead.| |false| |queryParamObjectFormat|The format for query param objects: 'dot', 'json', 'key'.| |dot| |serviceFileSuffix|The suffix of the file of the generated service (service<suffix>.ts).| |.service| |serviceSuffix|The suffix of the generated service.| |Service| diff --git a/modules/openapi-generator-gradle-plugin/gradle.properties b/modules/openapi-generator-gradle-plugin/gradle.properties index c8b12097262..84128661880 100644 --- a/modules/openapi-generator-gradle-plugin/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/gradle.properties @@ -1,5 +1,6 @@ # RELEASE_VERSION openApiGeneratorVersion=5.1.0-SNAPSHOT +>>>>>>> origin/master # /RELEASE_VERSION # BEGIN placeholders 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 f64d2d99d3f..dbc59ae281c 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 @@ -143,7 +143,111 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf "_Imaginary", "_Noreturn", "_Static_assert", - "_Thread_local") + "_Thread_local", + + // cpp reserved keywords + // ref: https://en.cppreference.com/w/cpp/keyword + "alignas", + "alignof", + "and", + "and_eq", + "asm", + "atomic_cancel", + "atomic_commit", + "atomic_noexcept", + //"auto", + "bitand", + "bitor", + "bool", + //"break", + //"case", + "catch", + //"char", + "char8_t", + "char16_t", + "char32_t", + "class", + "compl", + "concept", + //"const", + "consteval", + "constexpr", + "constinit", + "const_cast", + //"continue", + "co_await", + "co_return", + "co_yield", + "decltype", + //"default", + "delete", + //"do", + //"double", + "dynamic_cast", + //"else", + //"enum", + "explicit", + "export", + //"extern", + "false", + //"float", + //"for", + "friend", + //"goto", + //"if", + //"inline", + //"int", + //"long", + "mutable", + "namespace", + "new", + "noexcept", + "not", + "not_eq", + "nullptr", + "operator", + "or", + "or_eq", + "private", + "protected", + "public", + "reflexpr", + //"register", + "reinterpret_cast", + "requires", + //"return", + //"short", + //"signed", + //"sizeof", + //"static", + "static_assert", + "static_cast", + //"struct", + //"switch", + "synchronized", + "template", + "this", + "thread_local", + "throw", + "true", + "try", + //"typedef", + "typeid", + "typename", + //"union", + //"unsigned", + "using", + "virtual", + //"void", + //"volatile", + "wchar_t", + //"while", + "xor", + "xor_eq", + "final", + "override", + "transaction_safe", + "transaction_safe_dynamic") ); instantiationTypes.clear(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index 9d569156159..12e3e15bb85 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -787,8 +787,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } // string - String var = value.replaceAll("_", " "); - //var = WordUtils.capitalizeFully(var); + String var = value.replaceAll(" ", "_"); var = camelize(var); var = var.replaceAll("\\W+", ""); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java index c2cadfa1702..fcbc97b46e8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java @@ -22,6 +22,7 @@ import io.swagger.v3.oas.models.media.Schema; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; +import org.apache.commons.lang3.StringUtils; import java.util.*; @@ -123,6 +124,11 @@ public class ConfluenceWikiCodegen extends DefaultCodegen implements CodegenConf return objs; } + @Override + public Map postProcessModels(Map objs) { + return postProcessModelsEnum(objs); + } + @Override public String escapeQuotationMark(String input) { // just return the original string @@ -134,4 +140,14 @@ public class ConfluenceWikiCodegen extends DefaultCodegen implements CodegenConf // just return the original string return input; } + + @Override + public String escapeText(String input) { + if (input == null) { + return input; + } + + // chomp tailing newline because it breaks the tables and keep all other sign to show documentation properly + return StringUtils.chomp(input); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java new file mode 100644 index 00000000000..7a5b347180d --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -0,0 +1,891 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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 + * + * https://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.languages; + +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.templating.mustache.PrefixWithHashLambda; +import org.openapitools.codegen.templating.mustache.TrimWhitespaceLambda; +import org.openapitools.codegen.utils.ModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.*; + +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; + +public class CrystalClientCodegen extends DefaultCodegen { + private static final Logger LOGGER = LoggerFactory.getLogger(CrystalClientCodegen.class); + private static final String NUMERIC_ENUM_PREFIX = "N"; + protected static int emptyMethodNameCounter = 0; + + protected String shardName; + protected String moduleName; + protected String shardVersion = "1.0.0"; + protected String specFolder = "spec"; + protected String srcFolder = "src"; + protected String shardLicense = "unlicense"; + protected String shardHomepage = "https://openapitools.org"; + protected String shardSummary = "A Crystal SDK for the REST API"; + protected String shardDescription = "This shard maps to a REST API"; + protected String shardAuthor = ""; + protected String shardAuthorEmail = ""; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + public static final String SHARD_NAME = "shardName"; + public static final String SHARD_VERSION = "shardVersion"; + public static final String SHARD_LICENSE = "shardLicense"; + public static final String SHARD_HOMEPAGE = "shardHomepage"; + public static final String SHARD_SUMMARY = "shardSummary"; + public static final String SHARD_DESCRIPTION = "shardDescription"; + public static final String SHARD_AUTHOR = "shardAuthor"; + public static final String SHARD_AUTHOR_EMAIL = "shardAuthorEmail"; + + public CrystalClientCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.BearerToken, + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling, + GlobalFeature.ParameterizedServer, + GlobalFeature.MultiServer + ) + .includeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + .includeClientModificationFeatures( + ClientModificationFeature.BasePath, + ClientModificationFeature.UserAgent + ) + ); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + supportsInheritance = true; + + // clear import mapping (from default generator) as crystal does not use it + // at the moment + importMapping.clear(); + + embeddedTemplateDir = templateDir = "crystal"; + outputFolder = "generated-code" + File.separator + "crystal"; + + modelPackage = "models"; + apiPackage = "api"; + modelTemplateFiles.put("model.mustache", ".cr"); + apiTemplateFiles.put("api.mustache", ".cr"); + + modelTestTemplateFiles.put("model_test.mustache", ".cr"); + apiTestTemplateFiles.put("api_test.mustache", ".cr"); + + // TODO support auto-generated doc + //modelDocTemplateFiles.put("model_doc.mustache", ".md"); + //apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + + // reserved word. Ref: https://github.com/crystal-lang/crystal/wiki/Crystal-for-Rubyists#available-keywords + reservedWords = new HashSet( + Arrays.asList( + "abstract", "do", "if", "nil?", "select", "union", + "alias", "else", "in", "of", "self", "unless", + "as", "elsif", "include", "out", "sizeof", "until", + "as?", "end", "instance", "sizeof", "pointerof", "struct", "verbatim", + "asm", "ensure", "is_a?", "private", "super", "when", + "begin", "enum", "lib", "protected", "then", "while", + "break", "extend", "macro", "require", "true", "with", + "case", "false", "module", "rescue", "type", "yield", + "class", "for", "next", "responds_to?", "typeof", + "def", "fun", "nil", "return", "uninitialized") + ); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("String"); + languageSpecificPrimitives.add("Boolean"); + languageSpecificPrimitives.add("Integer"); + languageSpecificPrimitives.add("Float"); + languageSpecificPrimitives.add("Date"); + languageSpecificPrimitives.add("Time"); + languageSpecificPrimitives.add("Array"); + languageSpecificPrimitives.add("Hash"); + languageSpecificPrimitives.add("File"); + languageSpecificPrimitives.add("Object"); + + typeMapping.clear(); + typeMapping.put("string", "String"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("char", "Char"); + typeMapping.put("int", "Int32"); + typeMapping.put("integer", "Int32"); + typeMapping.put("long", "Int64"); + typeMapping.put("short", "Int32"); + typeMapping.put("float", "Float32"); + typeMapping.put("double", "Float64"); + typeMapping.put("number", "Float64"); + typeMapping.put("date", "Time"); + typeMapping.put("DateTime", "Time"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("set", "Set"); + typeMapping.put("map", "Hash"); + typeMapping.put("object", "Object"); + typeMapping.put("file", "File"); + typeMapping.put("binary", "String"); + typeMapping.put("ByteArray", "String"); + typeMapping.put("UUID", "String"); + typeMapping.put("URI", "String"); + + instantiationTypes.put("map", "Hash"); + instantiationTypes.put("array", "Array"); + instantiationTypes.put("set", "Set"); + + // remove modelPackage and apiPackage added by default + cliOptions.removeIf(opt -> CodegenConstants.MODEL_PACKAGE.equals(opt.getOpt()) || + CodegenConstants.API_PACKAGE.equals(opt.getOpt())); + + cliOptions.add(new CliOption(SHARD_NAME, "shard name (e.g. twitter_client"). + defaultValue("openapi_client")); + + cliOptions.add(new CliOption(SHARD_VERSION, "shard version.").defaultValue("1.0.0")); + + cliOptions.add(new CliOption(SHARD_LICENSE, "shard license."). + defaultValue("unlicense")); + + cliOptions.add(new CliOption(SHARD_HOMEPAGE, "shard homepage."). + defaultValue("http://org.openapitools")); + + cliOptions.add(new CliOption(SHARD_DESCRIPTION, "shard description."). + defaultValue("This shard maps to a REST API")); + + cliOptions.add(new CliOption(SHARD_AUTHOR, "shard author (only one is supported).")); + + cliOptions.add(new CliOption(SHARD_AUTHOR_EMAIL, "shard author email (only one is supported).")); + + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC). + defaultValue(Boolean.TRUE.toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (StringUtils.isEmpty(System.getenv("CRYSTAL_POST_PROCESS_FILE"))) { + LOGGER.info("Hint: Environment variable 'CRYSTAL_POST_PROCESS_FILE' (optional) not defined. E.g. to format the source code, please try 'export CRYSTAL_POST_PROCESS_FILE=\"/usr/local/bin/crystal tool format\"' (Linux/Mac)"); + } + + if (additionalProperties.containsKey(SHARD_NAME)) { + setShardName((String) additionalProperties.get(SHARD_NAME)); + } + additionalProperties.put(SHARD_NAME, shardName); + + if (additionalProperties.containsKey(SHARD_VERSION)) { + setShardVersion((String) additionalProperties.get(SHARD_VERSION)); + } else { + // not set, pass the default value to template + additionalProperties.put(SHARD_VERSION, shardVersion); + } + + if (additionalProperties.containsKey(SHARD_LICENSE)) { + setShardLicense((String) additionalProperties.get(SHARD_LICENSE)); + } + + if (additionalProperties.containsKey(SHARD_HOMEPAGE)) { + setShardHomepage((String) additionalProperties.get(SHARD_HOMEPAGE)); + } + + if (additionalProperties.containsKey(SHARD_SUMMARY)) { + setShardSummary((String) additionalProperties.get(SHARD_SUMMARY)); + } + + if (additionalProperties.containsKey(SHARD_DESCRIPTION)) { + setShardDescription((String) additionalProperties.get(SHARD_DESCRIPTION)); + } + + if (additionalProperties.containsKey(SHARD_AUTHOR)) { + setShardAuthor((String) additionalProperties.get(SHARD_AUTHOR)); + } + + if (additionalProperties.containsKey(SHARD_AUTHOR_EMAIL)) { + setShardAuthorEmail((String) additionalProperties.get(SHARD_AUTHOR_EMAIL)); + } + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + // use constant model/api package (folder path) + setModelPackage("models"); + setApiPackage("api"); + + supportingFiles.add(new SupportingFile("shard_name.mustache", srcFolder, shardName + ".cr")); + String shardFolder = srcFolder + File.separator + shardName; + supportingFiles.add(new SupportingFile("api_error.mustache", shardFolder, "api_error.cr")); + supportingFiles.add(new SupportingFile("configuration.mustache", shardFolder, "configuration.cr")); + supportingFiles.add(new SupportingFile("api_client.mustache", shardFolder, "api_client.cr")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); + supportingFiles.add(new SupportingFile("shard.mustache", "", "shard.yml")); + + // crystal spec files + supportingFiles.add(new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.cr") + .doNotOverwrite()); + + // add lambda for mustache templates + additionalProperties.put("lambdaPrefixWithHash", new PrefixWithHashLambda()); + + } + + @Override + public String getHelp() { + return "Generates a Crystal client library (beta)."; + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "crystal"; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + srcFolder + File.separator + shardName + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + srcFolder + File.separator + shardName + File.separator + modelPackage.replace("/", File.separator); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + specFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String getSchemaType(Schema schema) { + String openAPIType = super.getSchemaType(schema); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = openAPIType; + } + + if (type == null) { + return null; + } + + return toModelName(type); + } + + @Override + public String toModelName(final String name) { + String modelName; + modelName = sanitizeName(name); + + if (!StringUtils.isEmpty(modelNamePrefix)) { + modelName = modelNamePrefix + "_" + modelName; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + modelName = modelName + "_" + modelNameSuffix; + } + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(modelName)) { + modelName = camelize("Model" + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // 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) + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(modelName); + } + + @Override + public String toModelFilename(String name) { + return underscore(toModelName(name)); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiFilename(final String name) { + // replace - with _ e.g. created-at => created_at + String filename = name; + if (apiNameSuffix != null && apiNameSuffix.length() > 0) { + filename = filename + "_" + apiNameSuffix; + } + + filename = filename.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.cr => phone_number_api.cr + return underscore(filename); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String toApiTestFilename(String name) { + return toApiFilename(name) + "_spec"; + } + + @Override + public String toModelTestFilename(String name) { + return toModelFilename(name) + "_spec"; + } + + @Override + public String toApiName(String name) { + return super.toApiName(name); + } + + @Override + public String toEnumValue(String value, String datatype) { + if ("Integer".equals(datatype) || "Float".equals(datatype)) { + return value; + } else { + return "\"" + escapeText(value) + "\""; + } + } + + @Override + public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + + // number + if ("Integer".equals(datatype) || "Float".equals(datatype)) { + String varName = name; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return NUMERIC_ENUM_PREFIX + varName; + } + + // string + String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return NUMERIC_ENUM_PREFIX + enumName; + } else { + return enumName; + } + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return NUMERIC_ENUM_PREFIX + enumName; + } else { + return enumName; + } + } + + @Override + public Map postProcessModels(Map objs) { + // process enum in models + return postProcessModelsEnum(objs); + } + + @Override + public String toOperationId(String operationId) { + // rename to empty_method_name_1 (e.g.) if method name is empty + if (StringUtils.isEmpty(operationId)) { + operationId = underscore("empty_method_name_" + emptyMethodNameCounter++); + LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + return operationId; + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + String newOperationId = underscore("call_" + operationId); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + return newOperationId; + } + + // operationId starts with a number + if (operationId.matches("^\\d.*")) { + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return underscore(sanitizeName(operationId)); + } + + @Override + public String toApiImport(String name) { + return shardName + "/" + apiPackage() + "/" + toApiFilename(name); + } + + public void setShardName(String shardName) { + this.shardName = shardName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public void setShardVersion(String shardVersion) { + this.shardVersion = shardVersion; + } + + public void setShardDescription(String shardDescription) { + this.shardDescription = shardDescription; + } + + public void setShardSummary(String shardSummary) { + this.shardSummary = shardSummary; + } + + public void setShardLicense(String shardLicense) { + this.shardLicense = shardLicense; + } + + public void setShardHomepage(String shardHomepage) { + this.shardHomepage = shardHomepage; + } + + public void setShardAuthor(String shardAuthor) { + this.shardAuthor = shardAuthor; + } + + public void setShardAuthorEmail(String shardAuthorEmail) { + this.shardAuthorEmail = shardAuthorEmail; + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + final Schema additionalProperties = getAdditionalProperties(schema); + + if (additionalProperties != null) { + codegenModel.additionalPropertiesType = getSchemaType(additionalProperties); + } + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + objs = super.postProcessOperationsWithModels(objs, allModels); + Map operations = (Map) objs.get("operations"); + HashMap modelMaps = new HashMap(); + HashMap processedModelMaps = new HashMap(); + + for (Object o : allModels) { + HashMap h = (HashMap) o; + CodegenModel m = (CodegenModel) h.get("model"); + modelMaps.put(m.classname, m); + } + + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + for (CodegenParameter p : op.allParams) { + p.vendorExtensions.put("x-crystal-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + processedModelMaps.clear(); + for (CodegenParameter p : op.requiredParams) { + p.vendorExtensions.put("x-crystal-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + processedModelMaps.clear(); + for (CodegenParameter p : op.optionalParams) { + p.vendorExtensions.put("x-crystal-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + processedModelMaps.clear(); + for (CodegenParameter p : op.bodyParams) { + p.vendorExtensions.put("x-crystal-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + processedModelMaps.clear(); + for (CodegenParameter p : op.pathParams) { + p.vendorExtensions.put("x-crystal-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + processedModelMaps.clear(); + } + + return objs; + } + + private String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps, HashMap processedModelMap) { + if (codegenParameter.isArray) { // array + return "[" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "]"; + } else if (codegenParameter.isMap) { + return "{ key: " + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}"; + } else if (codegenParameter.isPrimitiveType) { // primitive type + if (codegenParameter.isEnum) { + // When inline enum, set example to first allowable value + List values = (List) codegenParameter.allowableValues.get("values"); + codegenParameter.example = String.valueOf(values.get(0)); + } + if (codegenParameter.isString || "String".equalsIgnoreCase(codegenParameter.baseType)) { + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return "'" + codegenParameter.example + "'"; + } + return "'" + codegenParameter.paramName + "_example'"; + } else if (codegenParameter.isBoolean) { // boolean + if (Boolean.parseBoolean(codegenParameter.example)) { + return "true"; + } + return "false"; + } else if (codegenParameter.isUri) { + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return "'" + codegenParameter.example + "'"; + } + return "'https://example.com'"; + } else if (codegenParameter.isDateTime) { + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return "Time.parse('" + codegenParameter.example + "')"; + } + return "Time.now"; + } else if (codegenParameter.isDate) { + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return "Date.parse('" + codegenParameter.example + "')"; + } + return "Date.today"; + } else if (codegenParameter.isFile) { + return "File.new('/path/to/some/file')"; + } else if (codegenParameter.isInteger) { + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return codegenParameter.example; + } + return "37"; + } else { // number + if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) { + return codegenParameter.example; + } + return "3.56"; + } + } else { // model + // look up the model + if (modelMaps.containsKey(codegenParameter.dataType)) { + return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap); + } else { + //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType); + return "TODO"; + } + } + } + + private String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps, HashMap processedModelMap) { + if (codegenProperty.isArray) { // array + return "[" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + "]"; + } else if (codegenProperty.isMap) { + return "{ key: " + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + "}"; + } else if (codegenProperty.isPrimitiveType) { // primitive type + if (codegenProperty.isEnum) { + // When inline enum, set example to first allowable value + List values = (List) codegenProperty.allowableValues.get("values"); + codegenProperty.example = String.valueOf(values.get(0)); + } + if (codegenProperty.isString || "String".equalsIgnoreCase(codegenProperty.baseType)) { + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return "'" + codegenProperty.example + "'"; + } else { + return "'" + codegenProperty.name + "_example'"; + } + } else if (codegenProperty.isBoolean) { // boolean + if (Boolean.parseBoolean(codegenProperty.example)) { + return "true"; + } else { + return "false"; + } + } else if (codegenProperty.isUri) { + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return "'" + codegenProperty.example + "'"; + } + return "'https://example.com'"; + } else if (codegenProperty.isDateTime) { + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return "Time.parse('" + codegenProperty.example + "')"; + } + return "Time.now"; + } else if (codegenProperty.isDate) { + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return "Date.parse('" + codegenProperty.example + "')"; + } + return "Date.today"; + } else if (codegenProperty.isFile) { + return "File.new('/path/to/some/file')"; + } else if (codegenProperty.isInteger) { + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return codegenProperty.example; + } + return "37"; + } else { // number + if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) { + return codegenProperty.example; + } + return "3.56"; + } + } else { // model + // look up the model + if (modelMaps.containsKey(codegenProperty.dataType)) { + return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap); + } else { + //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType); + return "TODO"; + } + } + } + + private String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps, HashMap processedModelMap) { + // break infinite recursion. Return, in case a model is already processed in the current context. + String model = codegenModel.name; + if (processedModelMap.containsKey(model)) { + int count = processedModelMap.get(model); + if (count == 1) { + processedModelMap.put(model, 2); + } else if (count == 2) { + return ""; + } else { + throw new RuntimeException("Invalid count when constructing example: " + count); + } + } else if (codegenModel.isEnum) { + List> enumVars = (List>) codegenModel.allowableValues.get("enumVars"); + return moduleName + "::" + codegenModel.classname + "::" + enumVars.get(0).get("name"); + } else if (codegenModel.oneOf != null && !codegenModel.oneOf.isEmpty()) { + String subModel = (String) codegenModel.oneOf.toArray()[0]; + String oneOf = constructExampleCode(modelMaps.get(subModel), modelMaps, processedModelMap); + return oneOf; + } else { + processedModelMap.put(model, 1); + } + + List propertyExamples = new ArrayList<>(); + for (CodegenProperty codegenProperty : codegenModel.requiredVars) { + propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap)); + } + String example = moduleName + "::" + toModelName(model) + ".new"; + if (!propertyExamples.isEmpty()) { + example += "({" + StringUtils.join(propertyExamples, ", ") + "})"; + } + return example; + } + + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } + + @Override + public String getTypeDeclaration(Schema schema) { + if (ModelUtils.isArraySchema(schema)) { + Schema inner = ((ArraySchema) schema).getItems(); + return getSchemaType(schema) + "(" + getTypeDeclaration(inner) + ")"; + } else if (ModelUtils.isMapSchema(schema)) { + Schema inner = getAdditionalProperties(schema); + return getSchemaType(schema) + "(String, " + getTypeDeclaration(inner) + ")"; + } + + return super.getTypeDeclaration(schema); + } + + @Override + public String toInstantiationType(Schema schema) { + if (ModelUtils.isMapSchema(schema)) { + return instantiationTypes.get("map"); + } else if (ModelUtils.isArraySchema(schema)) { + String parentType; + if (ModelUtils.isSet(schema)) { + parentType = "set"; + } else { + parentType = "array"; + } + return instantiationTypes.get(parentType); + } + return super.toInstantiationType(schema); + } + + @Override + public String toDefaultValue(Schema p) { + p = ModelUtils.getReferencedSchema(this.openAPI, p); + if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); + } + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + if (p.getDefault() instanceof Date) { + Date date = (Date) p.getDefault(); + LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + return "Date.parse(\"" + String.format(Locale.ROOT, localDate.toString(), "") + "\")"; + } else if (p.getDefault() instanceof java.time.OffsetDateTime) { + return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")"; + } else { + return "'" + escapeText((String) p.getDefault()) + "'"; + } + } + } + + return null; + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + return datatype + "::" + value; + } + + @Override + public String toVarName(final String name) { + String varName; + // sanitize name + varName = sanitizeName(name); + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + varName = varName.toLowerCase(Locale.ROOT); + } + + // camelize (lower first character) the variable name + // petId => pet_id + varName = underscore(varName); + + // for reserved word or word starting with number, append _ + if (isReservedWord(varName) || varName.matches("^\\d.*")) { + varName = escapeReservedWord(varName); + } + + return varName; + } + + public String toRegularExpression(String pattern) { + return addRegularExpressionDelimiter(pattern); + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("=end", "=_end").replace("=begin", "=_begin").replace("#{", "\\#{"); + } + + @Override + public void postProcessFile(File file, String fileType) { + if (file == null) { + return; + } + String crystalPostProcessFile = System.getenv("CRYSTAL_POST_PROCESS_FILE"); + if (StringUtils.isEmpty(crystalPostProcessFile)) { + return; // skip if CRYSTAL_POST_PROCESS_FILE env variable is not defined + } + // only process files with cr extension + if ("cr".equals(FilenameUtils.getExtension(file.toString()))) { + String command = crystalPostProcessFile + " " + file.toString(); + try { + Process p = Runtime.getRuntime().exec(command); + int exitValue = p.waitFor(); + if (exitValue != 0) { + BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + LOGGER.error("Error running the command ({}). Exit value: {}, Error output: {}", command, exitValue, sb.toString()); + } else { + LOGGER.info("Successfully executed: " + command); + } + } catch (Exception e) { + LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); + } + } + } +} 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 5ebe5d5f5f0..ce6c6234c38 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 @@ -472,13 +472,16 @@ public class DartClientCodegen extends DefaultCodegen { } if (schema.getDefault() != null) { + if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) { + // this is currently not supported and would create compile errors + return null; + } if (ModelUtils.isStringSchema(schema)) { return "'" + schema.getDefault().toString().replace("'", "\\'") + "'"; } return schema.getDefault().toString(); - } else { - return null; } + return null; } @Override @@ -555,6 +558,18 @@ public class DartClientCodegen extends DefaultCodegen { } } } + for (CodegenParameter p : op.allParams) { + if (p.isContainer) { + final String type = p.isArray ? "array" : "map"; + if (typeMapping().containsKey(type)) { + final String value = typeMapping().get(type); + // Also add container imports for parameters. + if (needToImport(value)) { + op.imports.add(value); + } + } + } + } return op; } 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 ff934aa6161..582402c2251 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 @@ -126,6 +126,16 @@ public class DartDioClientCodegen extends DartClientCodegen { @Override public String toDefaultValue(Schema schema) { if (schema.getDefault() != null) { + if (ModelUtils.isArraySchema(schema)) { + return "ListBuilder()"; + } + if (ModelUtils.isMapSchema(schema)) { + return "MapBuilder()"; + } + if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) { + // this is currently not supported and would create compile errors + return null; + } if (ModelUtils.isStringSchema(schema)) { return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; } @@ -279,6 +289,7 @@ public class DartDioClientCodegen extends DartClientCodegen { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); + Set> serializers = new HashSet<>(); Set modelImports = new HashSet<>(); Set fullImports = new HashSet<>(); @@ -304,6 +315,13 @@ public class DartDioClientCodegen extends DartClientCodegen { param.baseType = "MultipartFile"; param.dataType = "MultipartFile"; } + if (param.isContainer) { + final Map serializer = new HashMap<>(); + serializer.put("isArray", param.isArray); + serializer.put("isMap", param.isMap); + serializer.put("baseType", param.baseType); + serializers.add(serializer); + } } op.vendorExtensions.put("x-is-json", isJson); @@ -317,7 +335,7 @@ public class DartDioClientCodegen extends DartClientCodegen { Set imports = new HashSet<>(); for (String item : op.imports) { if (needToImport(item)) { - if (importMapping().containsKey(item) && needToImport(item)) { + if (importMapping().containsKey(item)) { fullImports.add(importMapping().get(item)); } else { imports.add(underscore(item)); @@ -326,10 +344,19 @@ public class DartDioClientCodegen extends DartClientCodegen { } modelImports.addAll(imports); op.imports = imports; + + if (op.returnContainer != null) { + final Map serializer = new HashMap<>(); + serializer.put("isArray", Objects.equals("array", op.returnContainer)); + serializer.put("isMap", Objects.equals("map", op.returnContainer)); + serializer.put("baseType", op.returnBaseType); + serializers.add(serializer); + } } objs.put("modelImports", modelImports); objs.put("fullImports", fullImports); + objs.put("serializers", serializers); return objs; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java index 6c58e89d6d2..059d85cf2c8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java @@ -135,7 +135,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC protected Set typeNames = new HashSet(); protected Set modelTypeNames = new HashSet(); - final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application/.*json(;.*)?"); + final private static Pattern CONTAINS_JSON_MIME_PATTERN = Pattern.compile("(?i)application/.*json(;.*)?"); public CodegenType getTag() { return CodegenType.CLIENT; @@ -1054,7 +1054,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC String mimeType = getMimeDataType(mediaType); typeNames.add(mimeType); m.put(X_MEDIA_DATA_TYPE, mimeType); - if (isJsonMimeType(mediaType)) { + if (isJsonMimeType(mediaType) || ContainsJsonMimeType(mediaType)) { m.put(X_MEDIA_IS_JSON, "true"); } if (isWildcardMimeType(mediaType)) { @@ -1461,4 +1461,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } } } + static boolean ContainsJsonMimeType(String mime) { + return mime != null && CONTAINS_JSON_MIME_PATTERN.matcher(mime).matches(); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java new file mode 100644 index 00000000000..a21fe433bbf --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java @@ -0,0 +1,1222 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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 + * + * https://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.languages; + +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.commons.lang3.StringUtils; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.io.File; + +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import static org.openapitools.codegen.utils.StringUtils.*; + +// This code was almost entirely based on MySqlSchemaCodegen. + +@SuppressWarnings("unchecked") +public class KtormSchemaCodegen extends AbstractKotlinCodegen { + static Logger LOGGER = LoggerFactory.getLogger(KtormSchemaCodegen.class); + + public static final String VENDOR_EXTENSION_SCHEMA = "x-ktorm-schema"; + public static final String DEFAULT_DATABASE_NAME = "defaultDatabaseName"; + public static final String IMPORT_MODEL_PACKAGE_NAME = "importModelPackageName"; + public static final String IDENTIFIER_NAMING_CONVENTION = "identifierNamingConvention"; + public static final String PRIMARY_KEY_CONVENTION = "primaryKeyConvention"; + public static final String ADD_SURROGATE_KEY = "addSurrogateKey"; + public static final Integer IDENTIFIER_MAX_LENGTH = 255; + + protected String importModelPackageName = ""; + protected String defaultDatabaseName = "sqlite.db"; + protected String databaseNamePrefix = "_", databaseNameSuffix = ""; + protected String tableNamePrefix = "_", tableNameSuffix = ""; + protected String columnNamePrefix = "_", columnNameSuffix = ""; + protected String identifierNamingConvention = "original"; + protected String primaryKeyConvention = "id"; + protected boolean addSurrogateKey = false; + + protected Map sqlTypeMapping = new HashMap(); + + // https://ktorm.liuwj.me/api-docs/me.liuwj.ktorm.schema/index.html + protected class SqlType { + protected static final String Blob = "blob"; + protected static final String Boolean = "boolean"; + protected static final String Bytes = "bytes"; + protected static final String Date = "date"; + protected static final String DateTime = "datetime"; + protected static final String Decimal = "decimal"; + protected static final String Double = "double"; + protected static final String Float = "float"; + protected static final String Enum = "enum"; + protected static final String Int = "int"; + protected static final String Long = "long"; + protected static final String Text = "text"; + protected static final String Varchar = "varchar"; + protected static final String Json = "json"; + } + + public KtormSchemaCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.noneOf(WireFormatFeature.class)) + .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .clientModificationFeatures(EnumSet.noneOf(ClientModificationFeature.class)) + ); + + // http://www.sqlite.org/draft/tokenreq.html + // https://sqlite.org/src/file/src/parse.y + setReservedWordsLowerCase( + Arrays.asList( + // SQL reserved words + "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ALWAYS", + "ANALYZE", "AND", "ANY", "AS", "ASC", "ATTACH", "AUTOINCR", + "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BITAND", "BITNOT", + "BITOR", "BLOB", "BY", "CASCADE", "CASE", "CAST", "CHECK", + "COLLATE", "COLUMN", "COMMA", "COMMIT", "CONCAT", "CONFLICT", + "CONSTRAINT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", + "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", + "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", + "DO", "DOT", "DROP", "EACH", "ELSE", "END", "EQ", "ESCAPE", + "EXCEPT", "EXCLUDE", "EXCLUSIVE", "EXISTS", "EXPLAIN", "FAIL", + "FILTER", "FIRST", "FLOAT", "FOLLOWING", "FOR", "FOREIGN", "FROM", + "FULL", "GE", "GENERATED", "GLOB", "GROUP", "GROUPS", "GT", + "HAVING", "ID", "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", + "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", "INTEGER", + "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LAST", "LE", + "LEFT", "LIKE", "LIMIT", "LP", "LSHIFT", "LT", "MATCH", "MINUS", + "NATURAL", "NE", "NO", "NOT", "NOTHING", "NOTNULL", "NULL", "NULLS", + "OF", "OFFSET", "ON", "OR", "ORDER", "OTHERS", "OUTER", "OVER", + "PARTITION", "PLAN", "PLUS", "PRAGMA", "PRECEDING", "PRIMARY", + "QUERY", "RAISE", "RANGE", "RECURSIVE", "REFERENCES", "REGEXP", + "REINDEX", "RELEASE", "REM", "RENAME", "REPLACE", "RESTRICT", + "RIGHT", "ROLLBACK", "ROW", "ROWS", "RP", "RSHIFT", "SAVEPOINT", + "SELECT", "SET", "SLASH", "STAR", "STRING", "TABLE", "TEMP", + "TEMPORARY", "THEN", "TIES", "TO", "TRANSACTION", "TRIGGER", + "UNBOUNDED", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", + "VALUES", "VARIABLE", "VIEW", "VIRTUAL", "WHEN", "WHERE", + "WINDOW", "WITH", "WITHOUT" + ) + ); + + typeMapping = new HashMap(); + typeMapping.put("string", "kotlin.String"); + typeMapping.put("boolean", "kotlin.Boolean"); + typeMapping.put("integer", "kotlin.Int"); + typeMapping.put("float", "kotlin.Float"); + typeMapping.put("long", "kotlin.Long"); + typeMapping.put("double", "kotlin.Double"); + typeMapping.put("ByteArray", "kotlin.ByteArray"); + typeMapping.put("number", "java.math.BigDecimal"); + typeMapping.put("date-time", "java.time.LocalDateTime"); + typeMapping.put("date", "java.time.LocalDate"); + typeMapping.put("file", "java.io.File"); + typeMapping.put("array", "kotlin.Array"); + typeMapping.put("list", "kotlin.collections.List"); + typeMapping.put("set", "kotlin.collections.Set"); + typeMapping.put("map", "kotlin.collections.Map"); + typeMapping.put("object", "kotlin.Any"); + typeMapping.put("binary", "kotlin.ByteArray"); + typeMapping.put("Date", "java.time.LocalDate"); + typeMapping.put("DateTime", "java.time.LocalDateTime"); + //missing on baseclass + typeMapping.put("byte", "kotlin.Byte"); + typeMapping.put("short", "kotlin.Short"); + typeMapping.put("char", "kotlin.String"); + typeMapping.put("real", "kotlin.Double"); + typeMapping.put("UUID", "java.util.UUID"); //be explict + typeMapping.put("URI", "java.net.URI"); //be explict + typeMapping.put("decimal", "java.math.BigDecimal"); + typeMapping.put("BigDecimal", "java.math.BigDecimal"); + typeMapping.put("AnyType", "kotlin.Any"); + typeMapping.put("password", "kotlin.String"); //nice to have + + //mappings between kotlin and ktor + // ref: https://ktorm.liuwj.me/en/schema-definition.html + sqlTypeMapping.put("kotlin.String", SqlType.Text); + sqlTypeMapping.put("kotlin.Boolean", SqlType.Boolean); + sqlTypeMapping.put("kotlin.Byte", SqlType.Int); + sqlTypeMapping.put("kotlin.Short", SqlType.Int); + sqlTypeMapping.put("kotlin.Int", SqlType.Int); + sqlTypeMapping.put("kotlin.Long", SqlType.Long); + sqlTypeMapping.put("kotlin.Float", SqlType.Float); + sqlTypeMapping.put("kotlin.Double", SqlType.Double); + sqlTypeMapping.put("kotlin.ByteArray", SqlType.Blob); + sqlTypeMapping.put("kotlin.Array", SqlType.Blob); + sqlTypeMapping.put("kotlin.collections.List", SqlType.Blob); + sqlTypeMapping.put("kotlin.collections.Set", SqlType.Blob); + sqlTypeMapping.put("kotlin.collections.Map", SqlType.Blob); + sqlTypeMapping.put("kotlin.Any", SqlType.Blob); + sqlTypeMapping.put("java.io.File", SqlType.Blob); + sqlTypeMapping.put("java.math.BigDecimal", SqlType.Decimal); + sqlTypeMapping.put("java.time.LocalDateTime", SqlType.DateTime); + sqlTypeMapping.put("java.time.LocalDate", SqlType.Date); + sqlTypeMapping.put("java.util.UUID", SqlType.Text); + sqlTypeMapping.put("java.net.URI", SqlType.Text); + + artifactId = "ktorm"; + artifactVersion = "1.0.0"; + packageName = "org.openapitools.database"; + + outputFolder = "generated-code" + File.separator + "kotlin-client"; + embeddedTemplateDir = templateDir = "ktorm-schema"; + modelTemplateFiles.put("model.mustache", ".kt"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + modelPackage = packageName + ".models"; + importModelPackageName = modelPackage; + + // we don't clear clioptions from Kotlin + // cliOptions default redefinition need to be updated + updateOption(CodegenConstants.ARTIFACT_ID, artifactId); + updateOption(CodegenConstants.PACKAGE_NAME, packageName); + removeOption(CodegenConstants.API_SUFFIX); + removeOption(CodegenConstants.PARCELIZE_MODELS); + removeOption(CodegenConstants.SERIALIZABLE_MODEL); + removeOption(CodegenConstants.SERIALIZATION_LIBRARY); + addOption(DEFAULT_DATABASE_NAME, "Default database name for all queries", defaultDatabaseName); + addOption(IMPORT_MODEL_PACKAGE_NAME, "Package name of the imported models", importModelPackageName); + addOption(PRIMARY_KEY_CONVENTION, "Primary key naming convention", primaryKeyConvention); + addSwitch(ADD_SURROGATE_KEY, "Adds the surrogate key for all models that don't already have a primary key (named by the above convention)", addSurrogateKey); + + // we used to snake_case table/column names, let's add this option + CliOption identifierNamingOpt = new CliOption(IDENTIFIER_NAMING_CONVENTION, + "Naming convention of Ktorm identifiers(table names and column names). This is not related to database name which is defined by " + DEFAULT_DATABASE_NAME + " option"); + + identifierNamingOpt.addEnum("original", "Do not transform original names") + .addEnum("snake_case", "Use snake_case names") + .setDefault("original"); + + cliOptions.add(identifierNamingOpt); + + } + + public CodegenType getTag() { + return CodegenType.SCHEMA; + } + + public String getName() { + return "ktorm-schema"; + } + + public String getHelp() { + return "Generates a kotlin-ktorm schema (beta)"; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(DEFAULT_DATABASE_NAME)) { + if (additionalProperties.get(DEFAULT_DATABASE_NAME).equals("")) { + additionalProperties.remove(DEFAULT_DATABASE_NAME); + } else { + setDefaultDatabaseName((String) additionalProperties.get(DEFAULT_DATABASE_NAME)); + // default database name may be escaped, need to overwrite additional prop + additionalProperties.put(DEFAULT_DATABASE_NAME, getDefaultDatabaseName()); + } + } + + if (additionalProperties.containsKey(IDENTIFIER_NAMING_CONVENTION)) { + setIdentifierNamingConvention((String) additionalProperties.get(IDENTIFIER_NAMING_CONVENTION)); + } + + if (additionalProperties.containsKey(IMPORT_MODEL_PACKAGE_NAME)) { + setImportModelPackageName((String) additionalProperties.get(IMPORT_MODEL_PACKAGE_NAME)); + } + + if (additionalProperties.containsKey(PRIMARY_KEY_CONVENTION)) { + setPrimaryKeyConvention((String) additionalProperties.get(PRIMARY_KEY_CONVENTION)); + } + + if (additionalProperties.containsKey(ADD_SURROGATE_KEY)) { + setAddSurrogateKey(convertPropertyToBooleanAndWriteBack(ADD_SURROGATE_KEY)); + } + + // make model src path available in mustache template + additionalProperties.put("modelSrcPath", "./" + toSrcPath(modelPackage)); + + 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("ktorm_schema.mustache", "", "ktorm_schema.sql")); + } + + @Override + public Map postProcessModels(Map objs) { + objs = super.postProcessModels(objs); + + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel model = (CodegenModel) mo.get("model"); + String modelName = model.getName(); + String tableName = toTableName(modelName); + String modelDescription = model.getDescription(); + Map modelVendorExtensions = model.getVendorExtensions(); + Map ktormSchema = new HashMap(); + Map tableDefinition = new HashMap(); + + if (getIdentifierNamingConvention().equals("snake_case") && !modelName.equals(tableName)) { + // add original name in table comment + String commentExtra = "Original model name - " + modelName + "."; + modelDescription = (modelDescription == null || modelDescription.isEmpty()) ? commentExtra : modelDescription + ". " + commentExtra; + } + + if (modelVendorExtensions.containsKey(VENDOR_EXTENSION_SCHEMA)) { + // user already specified schema values + LOGGER.info("Found vendor extension in '" + modelName + "' model, autogeneration skipped"); + } else { + modelVendorExtensions.put(VENDOR_EXTENSION_SCHEMA, ktormSchema); + ktormSchema.put("tableDefinition", tableDefinition); + tableDefinition.put("tblName", tableName); + tableDefinition.put("tblComment", modelDescription); + } + + // check if we need to add the surrogate key + if (addSurrogateKey) { + boolean hasPrimaryKey = false; + for (CodegenProperty var : model.vars) { + if (var.getBaseName().equals(primaryKeyConvention)) { + hasPrimaryKey = true; + break; + } + } + if (!hasPrimaryKey) { + final IntegerSchema schema = new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT); + CodegenProperty cp = super.fromProperty(primaryKeyConvention, schema); + cp.setRequired(true); + model.vars.add(0, cp); + model.allVars.add(0, cp); + model.requiredVars.add(0, cp); + model.readWriteVars.add(0, cp); + postProcessModelProperty(model, cp); + objs = super.postProcessModels(objs); + } + } + } + + return objs; + } + + private class KtormSchema extends HashMap { + private static final long serialVersionUID = -9159755928980443880L; + } + + /** + * Processes each model's property mapped + * + * @param model codegen model + * @param property model's property + */ + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + Map relationDefinition = new HashMap(); + Map vendorExtensions = property.getVendorExtensions(); + KtormSchema ktormSchema = new KtormSchema(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String description = property.getDescription(); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + if (vendorExtensions.containsKey(VENDOR_EXTENSION_SCHEMA)) { + // user already specified schema values + LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + return; + } + + vendorExtensions.put(VENDOR_EXTENSION_SCHEMA, ktormSchema); + + if (getIdentifierNamingConvention().equals("snake_case") && !baseName.equals(colName)) { + // add original name in column comment + String commentExtra = "Original param name - " + baseName + "."; + description = (description == null || description.isEmpty()) ? commentExtra : description + ". " + commentExtra; + } + + switch (actualType) { + case SqlType.Boolean: + processBooleanTypeProperty(model, property, description, ktormSchema); + break; + case SqlType.Int: + case SqlType.Long: + processIntegerTypeProperty(model, property, description, ktormSchema); + break; + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + processRealTypeProperty(model, property, description, ktormSchema); + break; + case SqlType.Blob: + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Bytes: + processStringTypeProperty(model, property, description, ktormSchema); + break; + case SqlType.Date: + case SqlType.DateTime: + processDateTypeProperty(model, property, description, ktormSchema); + break; + case SqlType.Json: + processJsonTypeProperty(model, property, description, ktormSchema); + break; + default: + processUnknownTypeProperty(model, property, description, ktormSchema); + } + + if (processForeignKey(model, property, relationDefinition)) { + ktormSchema.put("relationDefinition", relationDefinition); + ktormSchema.put("relation", true); + } + } + + /** + * Processes each model's property mapped to integer type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processIntegerTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + String minimum = property.getMinimum(); + String maximum = property.getMaximum(); + boolean exclusiveMinimum = property.getExclusiveMinimum(); + boolean exclusiveMaximum = property.getIExclusiveMaximum(); + boolean unsigned = false; + Boolean isUuid = property.isUuid; + + Long cmin = (minimum != null) ? Long.parseLong(minimum) : null; + Long cmax = (maximum != null) ? Long.parseLong(maximum) : null; + if (exclusiveMinimum && cmin != null) cmin += 1; + if (exclusiveMaximum && cmax != null) cmax -= 1; + if (cmin != null && cmin >= 0) { + unsigned = true; + } + long min = (cmin != null) ? cmin : Long.MIN_VALUE; + long max = (cmax != null) ? cmax : Long.MAX_VALUE; + long actualMin = Math.min(min, max); // sometimes min and max values can be mixed up + long actualMax = Math.max(min, max); // sometimes only minimum specified and it can be pretty high + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + columnDefinition.put("colUnsigned", unsigned); + columnDefinition.put("colMinimum", actualMin); + columnDefinition.put("colMaximum", actualMax); + columnDefinition.put("colIsUuid", isUuid); + + processTypeArgs(dataType, dataFormat, actualMin, actualMax, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property mapped to some real type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processRealTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + String minimum = property.getMinimum(); + String maximum = property.getMaximum(); + boolean exclusiveMinimum = property.getExclusiveMinimum(); + boolean exclusiveMaximum = property.getIExclusiveMaximum(); + + Float cmin = (minimum != null) ? Float.parseFloat(minimum) : null; + Float cmax = (maximum != null) ? Float.parseFloat(maximum) : null; + if (exclusiveMinimum && cmin != null) cmin += 1; + if (exclusiveMaximum && cmax != null) cmax -= 1; + Float min = (cmin != null) ? cmin : Float.MIN_VALUE; + Float max = (cmax != null) ? cmax : Float.MAX_VALUE; + Float actualMin = Math.min(min, max); // sometimes min and max values can be mixed up + Float actualMax = Math.max(min, max); // sometimes only minimum specified and it can be pretty high + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + columnDefinition.put("colMinimum", actualMin); + columnDefinition.put("colMaximum", actualMax); + + processTypeArgs(dataType, dataFormat, actualMin, actualMax, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property mapped to boolean type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processBooleanTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + + processTypeArgs(dataType, dataFormat, 0, 1, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property mapped to string type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processStringTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + Integer minLength = property.getMinLength(); + Integer maxLength = property.getMaxLength(); + + Integer min = (minLength != null) ? minLength : 0; + Integer max = (maxLength != null) ? maxLength : Integer.MAX_VALUE; + int actualMin = Math.min(min, max); // sometimes min and max values can be mixed up + int actualMax = Math.max(min, max); // sometimes only minimum specified and it can be pretty high + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + if (actualMin != 0) { + columnDefinition.put("colMinimum", actualMin); + } + if (actualMax != Integer.MAX_VALUE) { + columnDefinition.put("colMaximum", actualMax); + } + + processTypeArgs(dataType, dataFormat, actualMin, actualMax, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property mapped to date type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processDateTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + + processTypeArgs(dataType, dataFormat, null, null, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property mapped to JSON type and adds related vendor extensions + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processJsonTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + + processTypeArgs(dataType, dataFormat, null, null, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property not mapped to any type and adds related + * vendor extensions Most of time it's related to referenced properties eg. + * \Model\User + * + * @param model codegen model + * @param property model's property + * @param description property custom description + * @param ktormSchema schema + */ + public void processUnknownTypeProperty(CodegenModel model, CodegenProperty property, String description, KtormSchema ktormSchema) { + Map columnDefinition = new HashMap(); + String baseName = property.getBaseName(); + String colName = toColumnName(baseName); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String actualType = toColumnType(dataType, dataFormat); + + ktormSchema.put("columnDefinition", columnDefinition); + columnDefinition.put("colName", colName); + columnDefinition.put("colType", actualType); + columnDefinition.put("colKotlinType", dataType); + + processTypeArgs(dataType, dataFormat, null, null, columnDefinition); + processNullAndDefault(model, property, description, columnDefinition); + } + + /** + * Processes each model's property type arguments definitions + * + * @param dataType the choosen sql type + * @param dataFormat the choosen sql format + * @param min the minimum value, if specified, in the target type + * @param max the maximum value, if specified, in the target type + * @param columnDefinition resulting column definition dictionary + */ + public void processTypeArgs(String dataType, String dataFormat, Object min, Object max, Map columnDefinition) { + HashMap a = new HashMap(); + SqlTypeArgs args = new SqlTypeArgs(); + toColumnTypeArgs(dataType, dataFormat, min, max, args); + a.put("isPrimitive", args.isPrimitive); + a.put("isNumeric", args.isNumeric); + a.put("isBoolean", args.isBoolean); + a.put("isInteger", args.isInteger); + a.put("isFloat", args.isFloat); + a.put("isDecimal", args.isDecimal); + a.put("isString", args.isString); + a.put("isDate", args.isDate); + a.put("isDateTime", args.isDateTime); + a.put("isBlob", args.isBlob); + a.put("isJson", args.isJson); + a.put("isNull", args.isNull); + //as we are using sqlite, it is not implemented for now + //columnDefinition.put("colTypeArgs", a); + columnDefinition.put("colPrimaryKey", isPrimaryKey(columnDefinition)); + } + + /** + * Processes each model's property null/default definitions + * + * @param model model's name + * @param property model's property + * @param description property's customized description + * @param columnDefinition resulting column definition dictionary + */ + public void processNullAndDefault(CodegenModel model, CodegenProperty property, String description, Map columnDefinition) { + String baseName = property.getBaseName(); + Boolean required = property.getRequired(); + String dataType = property.getDataType(); + String dataFormat = property.getDataFormat(); + String defaultValue = property.getDefaultValue(); + if (Boolean.TRUE.equals(required)) { + columnDefinition.put("colNotNull", true); + } else { + columnDefinition.put("colNotNull", false); + try { + columnDefinition.put("colDefault", toColumnTypeDefault(defaultValue, dataType, dataFormat)); + } catch (RuntimeException exception) { + LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to data type which doesn't support default value"); + columnDefinition.put("colDefault", null); + } + } + if (description != null) { + columnDefinition.put("colComment", description); + } + } + + /** + * Processes each model's property that relates to another model + * + * @param model model's name + * @param property model's property + * @param relationDefinition resulting relation definition dictionary + * @return did we create the foreign key section. + */ + public boolean processForeignKey(CodegenModel model, CodegenProperty property, Map relationDefinition) { + String dataType = property.getDataType(); + if (!property.isArray && !isRelation(dataType)) return false; + + String modelName = model.getName(); + String tryDataType = property.isArray ? property.items.dataType : property.dataType; + String tryDataFormat = property.isArray ? property.items.dataFormat : property.dataFormat; + Boolean isPrimitive = (tryDataType.startsWith("kotlin.") || tryDataType.startsWith("java.")); + String propName = isPrimitive ? property.getName() : tryDataType; + + String pkName = toTitleCase(toModelName(modelName)); + String pkColName = toColumnName(pkName); + String fkName = toTitleCase(toModelName(propName)); + String fkColName = toColumnName(fkName); + String relName = toModelName(camelize(modelName) + camelize(propName)); + String relTblName = toTableName(relName); + + final IntegerSchema pkSchema = new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT); + String pkDataType = getSchemaType(pkSchema); + String pkDataFormat = pkSchema.getFormat(); + String pkColType = toColumnType(pkDataType, pkDataFormat); + String fkDataType = isPrimitive ? tryDataType : pkDataType; + String fkDataFormat = isPrimitive ? tryDataFormat : pkDataFormat; + String fkColType = toColumnType(fkDataType, fkDataFormat); + + SqlTypeArgs pkArgs = new SqlTypeArgs(); + toColumnTypeArgs(pkDataType, pkDataFormat, null, null, pkArgs); + SqlTypeArgs fkArgs = new SqlTypeArgs(); + toColumnTypeArgs(fkDataType, fkDataFormat, null, null, fkArgs); + + relationDefinition.put("pkName", pkName); + relationDefinition.put("pkColName", pkColName); + relationDefinition.put("pkColType", pkColType); + relationDefinition.put("pkColKotlinType", pkDataType); + relationDefinition.put("pkIsNumeric", pkArgs.isNumeric); + relationDefinition.put("pkIsInteger", pkArgs.isInteger); + relationDefinition.put("pkIsString", pkArgs.isString); + relationDefinition.put("pkIsPrimitive", pkArgs.isPrimitive); + + relationDefinition.put("fkName", fkName); + relationDefinition.put("fkColName", fkColName); + relationDefinition.put("fkColType", fkColType); + relationDefinition.put("fkColKotlinType", fkDataType); + relationDefinition.put("fkIsNumeric", fkArgs.isNumeric); + relationDefinition.put("fkIsInteger", fkArgs.isInteger); + relationDefinition.put("fkIsString", fkArgs.isString); + relationDefinition.put("fkIsPrimitive", fkArgs.isPrimitive); + + relationDefinition.put("relName", relName); + relationDefinition.put("relTblName", relTblName); + + return true; + } + + private String toTitleCase(final String input) { + return input.substring(0, 1).toLowerCase(Locale.ROOT) + input.substring(1); + } + + private class SqlTypeArgs { + // type classes + public boolean isPrimitive; + public boolean isNumeric; + // specific types + public boolean isBoolean; + public boolean isInteger; + public boolean isFloat; + public boolean isDecimal; + public boolean isString; + public boolean isDate; + public boolean isDateTime; + public boolean isBlob; + public boolean isJson; + // special args + public boolean isNull; + } + + /** + * Checks if the model type should be a relationship instead. + * + * @param columnDefinition resulting column definition dictionary + * @return is a relation + */ + private boolean isPrimaryKey(Map columnDefinition) { + String colName = (String) columnDefinition.get("colName"); + return colName.equals(primaryKeyConvention); + } + + /** + * Checks if the model type should be a relationship instead. + * + * @param dataType type name + * @return is a relation + */ + private boolean isRelation(String dataType) { + String sqlType = sqlTypeMapping.getOrDefault(dataType, "").toLowerCase(Locale.ROOT); + switch (sqlType) { + case SqlType.Boolean: + case SqlType.Int: + case SqlType.Long: + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Date: + case SqlType.DateTime: + case SqlType.Blob: + case SqlType.Json: + return false; + default: + // If its explicitly configured kotlin.* and java.* types. + if (dataType.startsWith("kotlin.") || dataType.startsWith("java.")) { + // We just have to serialize it. + return false; + } + // Otherwise we assume this is a legitimate model name and it becomes a foreign key. + return true; + } + } + + /** + * Generates codegen type mapping between ktor and sqlite + * Ref: http://www.sqlite.org/draft/datatype3.html + * + * @param dataType type name + * @param dataFormat type format + * @return generated codegen type + */ + private String toColumnType(String dataType, String dataFormat) { + String sqlType = sqlTypeMapping.getOrDefault(dataType, "").toLowerCase(Locale.ROOT); + switch (sqlType) { + case SqlType.Boolean: + case SqlType.Int: + case SqlType.Long: + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Date: + case SqlType.DateTime: + case SqlType.Blob: + case SqlType.Json: + return sqlType; + default: + return isRelation(dataType) ? SqlType.Long : SqlType.Blob; + } + } + + /** + * Generates codegen type argument mapping between ktor and sqlite + * Ref: http://www.sqlite.org/draft/datatype3.html + * + * @param dataType type name + * @param dataFormat type format + * @return generated codegen type + */ + private void toColumnTypeArgs(String dataType, String dataFormat, Object min, Object max, SqlTypeArgs args) { + String sqlType = toColumnType(dataType, dataFormat); + switch (sqlType) { + case SqlType.Boolean: + case SqlType.Int: + case SqlType.Long: + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Date: + case SqlType.DateTime: + args.isPrimitive = true; + break; + case SqlType.Blob: + case SqlType.Json: + default: + } + switch (sqlType) { + case SqlType.Boolean: + case SqlType.Int: + case SqlType.Long: + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + args.isNumeric = true; + break; + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Date: + case SqlType.DateTime: + case SqlType.Blob: + case SqlType.Json: + default: + } + switch (sqlType) { + case SqlType.Boolean: + args.isBoolean = true; + break; + case SqlType.Int: + case SqlType.Long: + args.isInteger = true; + break; + case SqlType.Float: + case SqlType.Double: + args.isFloat = true; + break; + case SqlType.Decimal: + args.isDecimal = true; + break; + case SqlType.Text: + case SqlType.Varchar: + args.isString = true; + break; + case SqlType.Date: + args.isDate = true; + break; + case SqlType.DateTime: + args.isDateTime = true; + break; + case SqlType.Blob: + args.isBlob = true; + break; + case SqlType.Json: + args.isJson = true; + break; + default: + args.isNull = true; + break; + } + } + + /** + * Generates codegen default value mapping between ktor and sqlite + * Ref: http://www.sqlite.org/draft/lang_createtable.html, sec3.2 + * + * @param defaultValue value + * @param dataType type name + * @param dataFormat type format + * @return generated codegen default + */ + private Map toColumnTypeDefault(String defaultValue, String dataType, String dataFormat) { + String sqlType = toColumnType(dataType, dataFormat); + String sqlDefault = ""; + if (defaultValue == null || defaultValue.toUpperCase(Locale.ROOT).equals("NULL")) { + sqlType = "null"; + } + //special case for keywords if needed + switch (sqlType) { + case SqlType.Boolean: + case SqlType.Int: + case SqlType.Long: + case SqlType.Float: + case SqlType.Double: + case SqlType.Decimal: + case SqlType.Text: + case SqlType.Varchar: + case SqlType.Date: + case SqlType.DateTime: + sqlDefault = defaultValue; + case SqlType.Blob: + case SqlType.Json: + throw new RuntimeException("The BLOB and JSON data types cannot be assigned a default value"); + default: + sqlDefault = "NULL"; + } + Map args = new HashMap(); + processTypeArgs(sqlType, null, null, null, args); + args.put("defaultValue", sqlDefault); + return args; + } + + /** + * Converts name to valid database name + * Produced name must be used with backticks only, eg. `database_name` + * + * @param name source name + * @return database name + */ + public String toDatabaseName(String name) { + String identifier = toIdentifier(name, databaseNamePrefix, databaseNameSuffix); + if (identifier.length() > IDENTIFIER_MAX_LENGTH) { + LOGGER.warn("Database name too long. Name '" + name + "' will be truncated"); + identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); + } + return identifier; + } + + /** + * Converts name to valid column name + * Produced name must be used with backticks only, eg. `table_name` + * + * @param name source name + * @return table name + */ + public String toTableName(String name) { + String identifier = toIdentifier(name, tableNamePrefix, tableNameSuffix); + if (identifierNamingConvention.equals("snake_case")) { + identifier = underscore(identifier); + } + if (identifier.length() > IDENTIFIER_MAX_LENGTH) { + LOGGER.warn("Table name too long. Name '" + name + "' will be truncated"); + identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); + } + return identifier; + } + + /** + * Converts name to valid column name + * Produced name must be used with backticks only, eg. `column_name` + * + * @param name source name + * @return column name + */ + public String toColumnName(String name) { + String identifier = toIdentifier(name, columnNamePrefix, columnNameSuffix); + if (identifierNamingConvention.equals("snake_case")) { + identifier = underscore(identifier); + } + if (identifier.length() > IDENTIFIER_MAX_LENGTH) { + LOGGER.warn("Column name too long. Name '" + name + "' will be truncated"); + identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); + } + return identifier; + } + + /** + * Converts name to valid identifier which can be used as database, table, column name + * Produced name must be used quoted only, eg. "column_name" + * + * @param name source name + * @param prefix when escaped name is digits only, prefix will be prepended + * @param suffix when escaped name is digits only, suffix will be appended + * @return identifier name + */ + public String toIdentifier(String name, String prefix, String suffix) { + String escapedName = escapeQuotedIdentifier(name); + // Database, table, and column names cannot end with space characters. + if (escapedName.matches(".*\\s$")) { + LOGGER.warn("Database, table, and column names cannot end with space characters. Check '" + name + "' name"); + escapedName = escapedName.replaceAll("\\s+$", ""); + } + + // Identifiers may begin with a digit but unless quoted may not consist solely of digits. + if (escapedName.matches("^\\d+$")) { + LOGGER.warn("Database, table, and column names cannot consist solely of digits. Check '" + name + "' name"); + escapedName = prefix + escapedName + suffix; + } + + // identifier name cannot be empty + if (escapedName.isEmpty()) { + throw new RuntimeException("Empty database/table/column name for property '" + name.toString() + "' not allowed"); + } + return escapedName; + } + + /** + * Escapes identifier to use it in SQL statements with backticks, eg. SELECT "identifier" FROM + * Ref: https://www.sqlite.org/draft/tokenreq.html H41130 + * Spec is similar to MySQL + * + * @param identifier source identifier + * @return escaped identifier + */ + public String escapeQuotedIdentifier(String identifier) { + // ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore) Extended: U+0080 .. U+FFFF + // ASCII NUL (U+0000) and supplementary characters (U+10000 and higher) are not permitted in quoted or unquoted identifiers. + // This does in fact matches against >\xFFFF and against ^\x0000. works only on Java7+ + Pattern regexp = Pattern.compile("[^0-9a-zA-z$_\\x0080-\\xFFFF]"); + Matcher matcher = regexp.matcher(identifier); + if (matcher.find()) { + LOGGER.warn("Identifier '" + identifier + "' contains unsafe characters out of [0-9,a-z,A-Z$_] and U+0080..U+FFFF range"); + identifier = identifier.replaceAll("[^0-9a-zA-z$_\\x0080-\\xFFFF]", ""); + } + return identifier; + } + + @Override + public String escapeReservedWord(String name) { + //LOGGER.warn("'" + name + "' is reserved word. Do not use that word or properly escape it with backticks in mustache template"); + return name; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + /** + * Sets default database name for all queries + * Provided value will be escaped when necessary + * + * @param databaseName source name + */ + public void setDefaultDatabaseName(String databaseName) { + String escapedName = toDatabaseName(databaseName); + if (!escapedName.equals(databaseName)) { + LOGGER.error("Invalid database name. '" + databaseName + "' cannot be used as identifier. Escaped value '" + escapedName + "' will be used instead."); + } + this.defaultDatabaseName = escapedName; + } + + /** + * Returns default database name for all queries + * This value must be used with backticks only, eg. `database_name` + * + * @return default database name + */ + public String getDefaultDatabaseName() { + return this.defaultDatabaseName; + } + + /** + * Sets imported package name for the models + * + * @param name name + */ + public void setImportModelPackageName(String name) { + this.importModelPackageName = name; + } + + /** + * Returns imported package name for the models + * + * @return name + */ + public String getImportModelPackageName() { + return this.importModelPackageName; + } + + /** + * Sets identifier naming convention for table names and column names. + * This is not related to database name which is defined by defaultDatabaseName option. + * + * @param naming identifier naming convention (original|snake_case) + */ + public void setIdentifierNamingConvention(String naming) { + switch (naming) { + case "original": + case "snake_case": + this.identifierNamingConvention = naming; + break; + default: + LOGGER.warn("\"" + (String) naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + (String) this.identifierNamingConvention + "\" used instead."); + } + } + + /** + * Returns identifier naming convention for table names and column names. + * + * @return identifier naming convention + */ + public String getIdentifierNamingConvention() { + return this.identifierNamingConvention; + } + + /** + * Sets primary key naming convenion + * + * @param name name + */ + public void setPrimaryKeyConvention(String name) { + this.primaryKeyConvention = name; + } + + /** + * Returns primary key naming convenion + * + * @return name + */ + public String getPrimaryKeyConvention() { + return this.primaryKeyConvention; + } + + /** + * Sets primary key naming convenion + * + * @param enable enable this option + */ + public void setAddSurrogateKey(boolean enable) { + this.addSurrogateKey = enable; + } + + /** + * Returns primary key naming convenion + * + * @return is enabled + */ + public boolean getAddSurrogateKey() { + return this.addSurrogateKey; + } + + /** + * Slightly modified version of AbstractPhpCodegen.toSrcPath method. + * + * @param packageName package name + * @return path + */ + public String toSrcPath(String packageName) { + // Trim prefix file separators from package path + String packagePath = StringUtils.removeStart( + // Replace period, backslash, forward slash with file separator in package name + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement("/")), + File.separator + ); + + // Trim trailing file separators from the overall path + return StringUtils.removeEnd(packagePath, File.separator); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java index ac119546ba1..d2b4a8d1ed2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java @@ -55,6 +55,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo protected HashSet methodNames; // store a list of method names to detect duplicates protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup protected boolean discardReadOnly = false; // Discard the readonly property in initialize cmdlet + protected boolean skipVerbParsing = false; // Attempt to parse cmdlets from operation names protected String projectUri; protected String licenseUri; protected String releaseNotes; @@ -511,6 +512,8 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo cliOptions.add(new CliOption("licenseUri","A URL to the license for the generated PowerShell module")); cliOptions.add(new CliOption("iconUri","A URL to an icon representing the generated PowerShell module")); cliOptions.add(new CliOption("releaseNotes","Release notes of the generated PowerShell module")); + cliOptions.add(new CliOption("skipVerbParsing", "Set skipVerbParsing to not try get powershell verbs of operation names")); + // option to change how we process + set the data in the 'additionalProperties' keyword. CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, @@ -601,6 +604,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo this.iconUri = iconUri; } + public void setSkipVerbParsing(boolean skipVerbParsing) { this.skipVerbParsing = skipVerbParsing; }; @Override public void processOpts() { @@ -628,7 +632,13 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo setDiscardReadOnly(convertPropertyToBooleanAndWriteBack("discardReadOnly")); } else { additionalProperties.put("discardReadOnly", discardReadOnly); - } + } + + if (additionalProperties.containsKey("skipVerbParsing")) { + setSkipVerbParsing(convertPropertyToBoolean("skipVerbParsing")); + } else { + additionalProperties.put("skipVerbParsing", skipVerbParsing); + } if (additionalProperties.containsKey("tags")) { String[] entries = ((String) additionalProperties.get("tags")).split(","); @@ -1212,20 +1222,22 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo private String toMethodName(String operationId) { String methodName = camelize(operationId); - // check if method name starts with powershell verbs - for (String verb : (HashSet) powershellVerbs) { - if (methodName.startsWith(verb)) { - methodName = verb + "-" + apiNamePrefix + methodName.substring(verb.length()); - LOGGER.info("Naming the method using the PowerShell verb: {} => {}", operationId, methodName); - return methodName; + if (!skipVerbParsing) { + // check if method name starts with powershell verbs + for (String verb : (HashSet) powershellVerbs) { + if (methodName.startsWith(verb)) { + methodName = verb + "-" + apiNamePrefix + methodName.substring(verb.length()); + LOGGER.info("Naming the method using the PowerShell verb: {} => {}", operationId, methodName); + return methodName; + } } - } - for (Map.Entry entry : commonVerbs.entrySet()) { - if (methodName.startsWith(entry.getKey())) { - methodName = entry.getValue() + "-" + apiNamePrefix + methodName.substring(entry.getKey().length()); - LOGGER.info("Naming the method by mapping the common verbs (e.g. Create, Change) to PS verbs: {} => {}", operationId, methodName); - return methodName; + for (Map.Entry entry : commonVerbs.entrySet()) { + if (methodName.startsWith(entry.getKey())) { + methodName = entry.getValue() + "-" + apiNamePrefix + methodName.substring(entry.getKey().length()); + LOGGER.info("Naming the method by mapping the common verbs (e.g. Create, Change) to PS verbs: {} => {}", operationId, methodName); + return methodName; + } } } 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 2a84a4fb6cd..534c5248293 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 @@ -16,6 +16,7 @@ package org.openapitools.codegen.languages; +import com.google.common.collect.Sets; import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.media.ArraySchema; @@ -879,7 +880,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { public String toExampleValue(Schema schema, Object objExample) { String modelName = getModelName(schema); - return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet()); } private Boolean simpleStringSchema(Schema schema) { @@ -925,9 +926,12 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * ModelName( line 0 * some_property='some_property_example' line 1 * ) line 2 + * @param seenSchemas This set contains all the schemas passed into the recursive function. It is used to check + * if a schema was already passed into the function and breaks the infinite recursive loop. The + * only schemas that are not added are ones that contain $ref != null * @return the string example */ - private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine) { + private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, Set seenSchemas) { final String indentionConst = " "; String currentIndentation = ""; String closingIndentation = ""; @@ -951,6 +955,27 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { if (objExample != null) { example = objExample.toString(); } + // checks if the current schema has already been passed in. If so, breaks the current recursive pass + if (seenSchemas.contains(schema)){ + if (modelName != null) { + return fullPrefix + modelName + closeChars; + } else { + // this is a recursive schema + // need to add a reasonable example to avoid + // infinite recursion + if(ModelUtils.isNullable(schema)) { + // if the schema is nullable, then 'None' is a valid value + return fullPrefix + "None" + closeChars; + } else if(ModelUtils.isArraySchema(schema)) { + // the schema is an array, add an empty array + return fullPrefix + "[]" + closeChars; + } else { + // the schema is an object, make an empty object + return fullPrefix + "{}" + closeChars; + } + } + } + if (null != schema.get$ref()) { Map allDefinitions = ModelUtils.getSchemas(this.openAPI); String ref = ModelUtils.getSimpleRef(schema.get$ref()); @@ -960,7 +985,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return fullPrefix + "None" + closeChars; } String refModelName = getModelName(schema); - return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine); + return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, seenSchemas); } else if (ModelUtils.isNullType(schema) || isAnyTypeSchema(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. @@ -1058,7 +1083,8 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { ArraySchema arrayschema = (ArraySchema) schema; Schema itemSchema = arrayschema.getItems(); String itemModelName = getModelName(itemSchema); - example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1) + ",\n" + closingIndentation + "]" + closeChars; + seenSchemas.add(schema); + example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, seenSchemas) + ",\n" + closingIndentation + "]" + closeChars; return example; } else if (ModelUtils.isMapSchema(schema)) { if (modelName == null) { @@ -1080,7 +1106,8 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { addPropPrefix = ensureQuotes(key) + ": "; } String addPropsModelName = getModelName(addPropsSchema); - example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1) + ",\n" + closingIndentation + closeChars; + seenSchemas.add(schema); + example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, seenSchemas) + ",\n" + closingIndentation + closeChars; } else { example = fullPrefix + closeChars; } @@ -1103,7 +1130,12 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return fullPrefix + closeChars; } } - return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation); + // Adds schema to seenSchemas before running example model function. romoves schema after running + // the function. It also doesnt keep track of any schemas within the ObjectModel. + seenSchemas.add(schema); + String exampleForObjectModel = exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, seenSchemas); + seenSchemas.remove(schema); + return exampleForObjectModel; } else if (ModelUtils.isComposedSchema(schema)) { // TODO add examples for composed schema models without discriminators @@ -1117,7 +1149,12 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { CodegenProperty cp = new CodegenProperty(); cp.setName(disc.getPropertyName()); cp.setExample(discPropNameValue); - return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation); + // Adds schema to seenSchemas before running example model function. romoves schema after running + // the function. It also doesnt keep track of any schemas within the ObjectModel. + seenSchemas.add(modelSchema); + String exampleForObjectModel = exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, seenSchemas); + seenSchemas.remove(modelSchema); + return exampleForObjectModel; } else { return fullPrefix + closeChars; } @@ -1130,7 +1167,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return example; } - private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation) { + private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, Set seenSchemas) { Map requiredAndOptionalProps = schema.getProperties(); if (requiredAndOptionalProps == null || requiredAndOptionalProps.isEmpty()) { return fullPrefix + closeChars; @@ -1150,7 +1187,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { propModelName = getModelName(propSchema); propExample = exampleFromStringOrArraySchema(propSchema, null, propName); } - example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1) + ",\n"; + example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1, seenSchemas) + ",\n"; } // TODO handle additionalProperties also example += closingIndentation + closeChars; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 10f44a3f937..bb86edadfef 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -522,7 +522,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig return ModelUtils.isSet(p) ? "Set<" + getTypeDeclaration(inner) + ">" : "[" + getTypeDeclaration(inner) + "]"; } else if (ModelUtils.isMapSchema(p)) { Schema inner = getAdditionalProperties(p); - return "[String:" + getTypeDeclaration(inner) + "]"; + return "[String: " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); } @@ -807,7 +807,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toEnumValue(String value, String datatype) { // for string, array of string - if ("String".equals(datatype) || "[String]".equals(datatype) || "[String:String]".equals(datatype)) { + if ("String".equals(datatype) || "[String]".equals(datatype) || "[String: String]".equals(datatype)) { return "\"" + String.valueOf(value) + "\""; } else { return String.valueOf(value); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 20f6ebe614b..e0d7c235a77 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -41,6 +41,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$"; public static enum QUERY_PARAM_OBJECT_FORMAT_TYPE {dot, json, key}; + public static enum PROVIDED_IN_LEVEL {none, root, any, platform}; private static final String DEFAULT_IMPORT_PREFIX = "./"; @@ -50,6 +51,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public static final String TAGGED_UNIONS = "taggedUnions"; public static final String NG_VERSION = "ngVersion"; public static final String PROVIDED_IN_ROOT = "providedInRoot"; + public static final String PROVIDED_IN = "providedIn"; public static final String ENFORCE_GENERIC_MODULE_WITH_PROVIDERS = "enforceGenericModuleWithProviders"; public static final String API_MODULE_PREFIX = "apiModulePrefix"; public static final String CONFIGURATION_PREFIX = "configurationPrefix"; @@ -72,6 +74,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode protected String fileNaming = "camelCase"; protected Boolean stringEnums = false; protected QUERY_PARAM_OBJECT_FORMAT_TYPE queryParamObjectFormat = QUERY_PARAM_OBJECT_FORMAT_TYPE.dot; + protected PROVIDED_IN_LEVEL providedIn = PROVIDED_IN_LEVEL.root; private boolean taggedUnions = false; @@ -104,8 +107,17 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode "Use discriminators to create tagged unions instead of extending interfaces.", this.taggedUnions)); this.cliOptions.add(CliOption.newBoolean(PROVIDED_IN_ROOT, - "Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).", + "Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0). IMPORTANT: Deprecated for angular version greater or equal to 9.0.0, use **providedIn** instead.", false)); + CliOption providedInCliOpt = new CliOption(PROVIDED_IN, + "Use this property to provide Injectables in wanted level (it is only valid in angular version greater or equal to 9.0.0).").defaultValue("root"); + Map providedInOptions = new HashMap<>(); + providedInOptions.put(PROVIDED_IN_LEVEL.none.toString(), "No providedIn (same as providedInRoot=false)"); + providedInOptions.put(PROVIDED_IN_LEVEL.root.toString(), "The application-level injector in most apps."); + providedInOptions.put(PROVIDED_IN_LEVEL.platform.toString(), "A special singleton platform injector shared by all applications on the page."); + providedInOptions.put(PROVIDED_IN_LEVEL.any.toString(), "Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance."); + providedInCliOpt.setEnum(providedInOptions); + this.cliOptions.add(providedInCliOpt); this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular. (At least 6.0.0)").defaultValue(this.ngVersion)); this.cliOptions.add(new CliOption(API_MODULE_PREFIX, "The prefix of the generated ApiModule.")); this.cliOptions.add(new CliOption(CONFIGURATION_PREFIX, "The prefix of the generated Configuration.")); @@ -188,13 +200,28 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString()); } - if (!additionalProperties.containsKey(PROVIDED_IN_ROOT)) { - additionalProperties.put(PROVIDED_IN_ROOT, true); + if (ngVersion.atLeast("9.0.0") && additionalProperties.containsKey(PROVIDED_IN)) { + setProvidedIn(additionalProperties.get(PROVIDED_IN).toString()); } else { - additionalProperties.put(PROVIDED_IN_ROOT, Boolean.parseBoolean( - additionalProperties.get(PROVIDED_IN_ROOT).toString() - )); + // Keep for backward compatibility + if (!additionalProperties.containsKey(PROVIDED_IN_ROOT)) { + additionalProperties.put(PROVIDED_IN_ROOT, true); + } else { + if (ngVersion.atLeast("9.0.0")) { + LOGGER.warn("{} will be deprecated, use {} {} instead", PROVIDED_IN_ROOT, PROVIDED_IN, PROVIDED_IN_LEVEL.values()); + } + additionalProperties.put(PROVIDED_IN_ROOT, Boolean.parseBoolean( + additionalProperties.get(PROVIDED_IN_ROOT).toString() + )); + } + if ((Boolean) additionalProperties.get(PROVIDED_IN_ROOT)) { + providedIn = PROVIDED_IN_LEVEL.root; + } else { + providedIn = PROVIDED_IN_LEVEL.none; + } } + additionalProperties.put("providedIn", providedIn); + additionalProperties.put("isProvidedInNone", getIsProvidedInNone()); if (ngVersion.atLeast("9.0.0")) { additionalProperties.put(ENFORCE_GENERIC_MODULE_WITH_PROVIDERS, true); @@ -714,5 +741,29 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } return name; } + + /** + * Set the Injectable level + * + * @param level the wanted level + */ + public void setProvidedIn (String level) { + try { + providedIn = PROVIDED_IN_LEVEL.valueOf(level); + } catch (IllegalArgumentException e) { + String values = Stream.of(PROVIDED_IN_LEVEL.values()) + .map(value -> "'" + value.name() + "'") + .collect(Collectors.joining(", ")); + String msg = String.format(Locale.ROOT, "Invalid providedIn level '%s'. Must be one of %s.", level, values); + throw new IllegalArgumentException(msg); + } + } + + /** + * + */ + private boolean getIsProvidedInNone() { + return PROVIDED_IN_LEVEL.none.equals(providedIn); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index cf591520be9..d845cb159cf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -219,6 +219,14 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege return objs; } + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + if (parameter.isFormParam && parameter.isArray && "binary".equals(parameter.dataFormat)) { + parameter.isCollectionFormatMulti = true; + } + } + @Override public Map postProcessAllModels(Map objs) { Map result = super.postProcessAllModels(objs); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PrefixWithHashLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PrefixWithHashLambda.java new file mode 100644 index 00000000000..c3418de09b7 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PrefixWithHashLambda.java @@ -0,0 +1,49 @@ +/* + * 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 + * + * https://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.templating.mustache; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template.Fragment; + +import java.io.IOException; +import java.io.Writer; + +/** + * Replaces duplicate whitespace characters in a fragment with single space. + * + * Register: + *
    + * additionalProperties.put("lambdaPrefixWithHash", new PrefixWithHashLambda());
    + * 
    + * + * Use: + *
    + * {{#lambdaPrefixWithHash}}{{name}}{{/lambdaPrefixWithHash}}
    + * 
    + */ +public class PrefixWithHashLambda implements Mustache.Lambda { + private static final String WITH_HASH = "\n#"; + + private static final String NEWLINE_REGEX = "\\R"; + + @Override + public void execute(Fragment fragment, Writer writer) throws IOException { + writer.write(fragment.execute().replaceAll(NEWLINE_REGEX, WITH_HASH)); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java index 9bca83d638b..d1ee6762b54 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java @@ -61,7 +61,7 @@ public class StringUtils { .build(); } - private static Pattern capitalLetterPattern = Pattern.compile("([A-Z]+)([A-Z][a-z])"); + private static Pattern capitalLetterPattern = Pattern.compile("([A-Z]+)([A-Z][a-z][a-z]+)"); private static Pattern lowercasePattern = Pattern.compile("([a-z\\d])([A-Z])"); private static Pattern pkgSeparatorPattern = Pattern.compile("\\."); private static Pattern dollarPattern = Pattern.compile("\\$"); 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 ff19d883490..0c85a67a2b3 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 @@ -116,13 +116,13 @@ end: {{#pathParams}} // Path Params - long sizeOfPathParams_{{{paramName}}} = {{#pathParams}}{{#isLong}}sizeof({{paramName}})+3{{/isLong}}{{#isString}}strlen({{paramName}})+3{{/isString}}{{^-last}} + {{/-last}}{{/pathParams}} + strlen("{ {{paramName}} }"); + long sizeOfPathParams_{{{paramName}}} = {{#pathParams}}{{#isLong}}sizeof({{paramName}})+3{{/isLong}}{{#isString}}strlen({{paramName}})+3{{/isString}}{{^-last}} + {{/-last}}{{/pathParams}} + strlen("{ {{baseName}} }"); {{#isNumeric}} if({{paramName}} == 0){ goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{paramName}}"); + snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{baseName}}"); char localVarBuff_{{paramName}}[256]; intToStr(localVarBuff_{{paramName}}, {{paramName}}); @@ -135,7 +135,7 @@ end: goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{paramName}}"); + snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{baseName}}"); char localVarBuff_{{paramName}}[256]; intToStr(localVarBuff_{{paramName}}, {{paramName}}); @@ -148,7 +148,7 @@ end: goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{paramName}}"); + snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{baseName}}"); char localVarBuff_{{paramName}}[256]; intToStr(localVarBuff_{{paramName}}, {{paramName}}); @@ -161,7 +161,7 @@ end: goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{paramName}}"); + snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{baseName}}"); char localVarBuff_{{paramName}}[256]; intToStr(localVarBuff_{{paramName}}, {{paramName}}); @@ -174,7 +174,7 @@ end: goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - sprintf(localVarToReplace_{{paramName}}, "{%s}", "{{paramName}}"); + sprintf(localVarToReplace_{{paramName}}, "{%s}", "{{baseName}}"); localVarPath = strReplace(localVarPath, localVarToReplace_{{paramName}}, {{paramName}}); {{/isString}} @@ -183,7 +183,7 @@ end: goto end; } char* localVarToReplace_{{paramName}} = malloc(sizeOfPathParams_{{paramName}}); - sprintf(localVarToReplace_{{paramName}}, "{%s}", "{{paramName}}"); + sprintf(localVarToReplace_{{paramName}}, "{%s}", "{{baseName}}"); localVarPath = strReplace(localVarPath, localVarToReplace_{{paramName}}, {{paramName}}); {{/isUuid}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 713332e20b7..e8833c12611 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -396,7 +396,7 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} { * * @param secrets Hash map from authentication name to its secret. */ - public ApiClient configureApiKeys(HashMap secrets) { + public ApiClient configureApiKeys(Map secrets) { for (Map.Entry authEntry : authentications.entrySet()) { Authentication auth = authEntry.getValue(); if (auth instanceof ApiKeyAuth) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache index a6687d778cd..315fcdd4415 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache @@ -522,6 +522,15 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} { return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); } + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -536,7 +545,7 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} { } for (String accept : accepts) { MediaType mediaType = MediaType.parseMediaType(accept); - if (isJsonMime(mediaType)) { + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { return Collections.singletonList(mediaType); } } 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 8fe400f1148..7a0d6556be6 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 @@ -7,6 +7,7 @@ org.openapitools.codegen.languages.AsciidocDocumentationCodegen org.openapitools.codegen.languages.AspNetCoreServerCodegen org.openapitools.codegen.languages.AvroSchemaCodegen org.openapitools.codegen.languages.BashClientCodegen +org.openapitools.codegen.languages.CrystalClientCodegen org.openapitools.codegen.languages.CLibcurlClientCodegen org.openapitools.codegen.languages.ClojureClientCodegen org.openapitools.codegen.languages.ConfluenceWikiCodegen @@ -44,6 +45,7 @@ org.openapitools.codegen.languages.KotlinClientCodegen org.openapitools.codegen.languages.KotlinServerCodegen org.openapitools.codegen.languages.KotlinSpringServerCodegen org.openapitools.codegen.languages.KotlinVertxServerCodegen +org.openapitools.codegen.languages.KtormSchemaCodegen org.openapitools.codegen.languages.HaskellHttpClientCodegen org.openapitools.codegen.languages.HaskellServantCodegen org.openapitools.codegen.languages.JavaClientCodegen diff --git a/modules/openapi-generator/src/main/resources/confluenceWikiDocs/index.mustache b/modules/openapi-generator/src/main/resources/confluenceWikiDocs/index.mustache index be2e6ccc807..9ddece9da19 100644 --- a/modules/openapi-generator/src/main/resources/confluenceWikiDocs/index.mustache +++ b/modules/openapi-generator/src/main/resources/confluenceWikiDocs/index.mustache @@ -75,10 +75,14 @@ h2. Models {anchor:{{classname}}ModelAnchor} h3. {{classname}} - {{description}} - - ||Field Name||Required||Type||Description||Enum|| + {{{description}}} + + {{#isEnum}} ||Name||Value||Description|| + {{#allowableValues}} {{#enumVars}} |{{{name}}} |{{{value}}} |{{{enumDescription}}} | + {{/enumVars}} + {{/allowableValues}} {{/isEnum}} + {{^isEnum}}||Field Name||Required||Type||Description||Enum|| {{#vars}} |{{baseName}} |{{#required}}(/){{/required}}{{^required}}(x){{/required}} |{noformat:nopanel=true}{{{dataType}}}{noformat} |{{description}} | {{#isEnum}} {{_enum}} {{/isEnum}} | - {{/vars}} + {{/vars}} {{/isEnum}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/crystal/Gemfile.mustache b/modules/openapi-generator/src/main/resources/crystal/Gemfile.mustache new file mode 100644 index 00000000000..c2e3127cdcf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/Gemfile.mustache @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/modules/openapi-generator/src/main/resources/crystal/README.mustache b/modules/openapi-generator/src/main/resources/crystal/README.mustache new file mode 100644 index 00000000000..20705236b9c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/README.mustache @@ -0,0 +1,46 @@ +# {{shardName}} + +The Crystsal module for the {{appName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{shardVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation + +### Install from Git + +Add the following to shard.yaml + +```yaml +dependencies: + {{{shardName}}}: + github: {{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_GIT_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}YOUR_GIT_REPO{{/gitRepoId}} + version: ~> {{shardVersion}} +``` + +## Development + +Install dependencies + +```shell +shards +``` + +Run the tests: + +```shell +crystal spec +``` diff --git a/modules/openapi-generator/src/main/resources/crystal/Rakefile.mustache b/modules/openapi-generator/src/main/resources/crystal/Rakefile.mustache new file mode 100644 index 00000000000..c72ca30d454 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/Rakefile.mustache @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/modules/openapi-generator/src/main/resources/crystal/api.mustache b/modules/openapi-generator/src/main/resources/crystal/api.mustache new file mode 100644 index 00000000000..550f017c4c6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api.mustache @@ -0,0 +1,185 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "uri" + +module {{moduleName}} +{{#operations}} + class {{classname}} + property api_client : ApiClient + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end +{{#operation}} + {{#summary}} + # {{{summary}}} + {{/summary}} + {{#notes}} + # {{{notes}}} + {{/notes}} + {{#allParams}} + {{#required}} + # @param {{paramName}} [{{{dataType}}}{{^required}}?{{/required}}] {{description}} + {{/required}} + {{/allParams}} + # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] + def {{operationId}}({{#allParams}}{{paramName}} : {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + {{#returnType}}data, _status_code, _headers = {{/returnType}}{{operationId}}_with_http_info({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) + {{#returnType}}data{{/returnType}}{{^returnType}}nil{{/returnType}} + end + + {{#summary}} + # {{summary}} + {{/summary}} + {{#notes}} + # {{notes}} + {{/notes}} + {{#allParams}} + {{#required}} + # @param {{paramName}} [{{{dataType}}}{{^required}}?{{/required}}] {{description}} + {{/required}} + {{/allParams}} + # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Integer, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers + def {{operationId}}_with_http_info({{#allParams}}{{paramName}} : {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + if @api_client.config.debugging + Log.debug {"Calling API: {{classname}}.{{operationId}} ..."} + end + {{#allParams}} + {{^isNullable}} + {{#required}} + # verify the required parameter "{{paramName}}" is set + if @api_client.config.client_side_validation && {{{paramName}}}.nil? + raise ArgumentError.new("Missing the required parameter '{{paramName}}' when calling {{classname}}.{{operationId}}") + end + {{#isEnum}} + {{^isContainer}} + # verify enum value + allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] + if @api_client.config.client_side_validation && !allowable_values.include?({{{paramName}}}) + raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}") + end + {{/isContainer}} + {{/isEnum}} + {{/required}} + {{/isNullable}} + {{^required}} + {{#isEnum}} + {{#collectionFormat}} + allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] + if @api_client.config.client_side_validation && {{{paramName}}} && {{{paramName}}}.all? { |item| allowable_values.include?(item) } + raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must include one of #{allowable_values}") + end + {{/collectionFormat}} + {{^collectionFormat}} + allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] + if @api_client.config.client_side_validation && {{{paramName}}} && !allowable_values.include?({{{paramName}}}]) + raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}") + end + {{/collectionFormat}} + {{/isEnum}} + {{/required}} + {{#hasValidation}} + {{#maxLength}} + if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.length > {{{maxLength}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.") + end + + {{/maxLength}} + {{#minLength}} + if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.length < {{{minLength}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.") + end + + {{/minLength}} + {{#maximum}} + if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.") + end + + {{/maximum}} + {{#minimum}} + if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.") + end + + {{/minimum}} + {{#pattern}} + pattern = Regexp.new({{{pattern}}}) + if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}} !~ pattern + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern #{pattern}.") + end + + {{/pattern}} + {{#maxItems}} + if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.length > {{{maxItems}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.") + end + + {{/maxItems}} + {{#minItems}} + if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.length < {{{minItems}}} + raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.") + end + + {{/minItems}} + {{/hasValidation}} + {{/allParams}} + # resource path + local_var_path = "{{{path}}}"{{#pathParams}}.sub("{" + "{{baseName}}" + "}", URI.encode({{paramName}}.to_s){{^strictSpecBehavior}}.gsub("%2F", "/"){{/strictSpecBehavior}}){{/pathParams}} + + # query parameters + query_params = Hash(Symbol, String).new + {{#queryParams}} + query_params[:"{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} + {{/queryParams}} + + # header parameters + header_params = Hash(String, String).new + {{#hasProduces}} + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept([{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}]) + {{/hasProduces}} + {{#hasConsumes}} + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type([{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}]) + {{/hasConsumes}} + {{#headerParams}} + header_params["{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} + {{/headerParams}} + + # form parameters + form_params = Hash(Symbol, String).new + {{#formParams}} + form_params[:"{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} + {{/formParams}} + + # http body (model) + post_body = {{#bodyParam}}{{{paramName}}}.to_json{{/bodyParam}}{{^bodyParam}}nil{{/bodyParam}} + + # return_type + return_type = {{#returnType}}"{{{.}}}"{{/returnType}}{{^returnType}}nil{{/returnType}} + + # auth_names + auth_names = {{#authMethods}}{{#-first}}[{{/-first}}"{{name}}"{{^-last}}, {{/-last}}{{#-last}}]{{/-last}}{{/authMethods}}{{^authMethods}}[] of String{{/authMethods}} + + data, status_code, headers = @api_client.call_api(:{{httpMethod}}, + local_var_path, + :"{{classname}}.{{operationId}}", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return {{#returnType}}{{{.}}}.from_json(data){{/returnType}}{{^returnType}}nil{{/returnType}}, status_code, headers + end +{{^-last}} + +{{/-last}} +{{/operation}} + end +{{/operations}} +end diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache new file mode 100644 index 00000000000..5352175b00e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache @@ -0,0 +1,402 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "json" +require "time" + +module {{moduleName}} + class ApiClient + # The Configuration object holding settings to be used in the API client. + property config : Configuration + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + property default_headers : Hash(String, String) + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(@config = Configuration.default) + @user_agent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/#{VERSION}/crystal{{/httpUserAgent}}" + @default_headers = { + "User-Agent" => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + + # handle file downloading - return the File instance processed in request callbacks + # note that response body is empty when the file is written in chunks in request on_body callback + if return_type == "File" + content_disposition = response.headers["Content-Disposition"].to_s + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition.match(/filename=[""]?([^""\s]+)[""]?/i).try &.[0] + prefix = sanitize_filename(filename) + else + prefix = "download-" + end + if !prefix.nil? && prefix.ends_with?("-") + prefix = prefix + "-" + end + encoding = response.headers["Content-Encoding"].to_s + + # TODO add file support + raise ApiError.new(code: 0, message: "File response not yet supported in the client.") if return_type + return nil + + #@tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + #@tempfile.write(@stream.join.force_encoding(encoding)) + #@tempfile.close + #Log.info { "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\ + # "with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\ + # "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + # "explicitly with `tempfile.delete`" } + #return @tempfile + end + + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body if return_type == "String" + + # ensuring a default content type + content_type = response.headers["Content-Type"] || "application/json" + + raise ApiError.new(code: 0, message: "Content-Type is not supported: #{content_type}") unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]")[0] + rescue e : Exception + if %w(String Date Time).includes?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when "String" + data.to_s + when "Integer" + data.to_s.to_i + when "Float" + data.to_s.to_f + when "Boolean" + data == true + when "Time" + # parse date time (expecting ISO 8601 format) + Time.parse! data.to_s, "%Y-%m-%dT%H:%M:%S%Z" + when "Date" + # parse date (expecting ISO 8601 format) + Time.parse! data.to_s, "%Y-%m-%d" + when "Object" + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + ({} of Symbol => String).tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + if filename.nil? + return nil + else + filename.gsub(/.*[\/\\]/, "") + end + end + + def build_request_url(path : String, operation : Symbol) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, "/") + @config.base_url(operation) + path + end + + # Update hearder and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array{auth_names}.each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when "header" then header_params[auth_setting[:key]] = auth_setting[:value] + when "query" then query_params[auth_setting[:key]] = auth_setting[:value] + else raise ArgumentError.new("Authentication token must be in `query` of `header`") + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers["User-Agent"] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) : String + #return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + if json_accept.nil? + accepts.join(",") + else + json_accept + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # use application/json by default + return "application/json" if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(",") + when :ssv + param.join(" ") + when :tsv + param.join("\t") + when :pipes + param.join("|") + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + #ssl_options = { + # :ca_file => @config.ssl_ca_file, + # :verify => @config.ssl_verify, + # :verify_mode => @config.ssl_verify_mode, + # :client_cert => @config.ssl_client_cert, + # :client_key => @config.ssl_client_key + #} + + #connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn| + # conn.basic_auth(config.username, config.password) + # if opts[:header_params]["Content-Type"] == "multipart/form-data" + # conn.request :multipart + # conn.request :url_encoded + # end + # conn.adapter(Faraday.default_adapter) + #end + + if !post_body.nil? && !post_body.empty? + # use JSON string in the payload + form_or_body = post_body + else + # use HTTP forms in the payload + # TDOD use HTTP form encoding + form_or_body = form_params + end + + request = Crest::Request.new(http_method, + build_request_url(path, operation), + params: query_params, + headers: header_params, + #cookies: cookie_params, # TODO add cookies support + form: form_or_body, + logging: @config.debugging, + handle_errors: false + ) + + response = request.execute + + if @config.debugging + Log.debug {"HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"} + end + + if !response.success? + if response.status == 0 + # Errors from libcurl will be made visible here + raise ApiError.new(code: 0, + message: response.body) + else + raise ApiError.new(code: response.status_code, + response_headers: response.headers, + message: response.body) + end + end + + return response.body, response.status_code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, request, opts = {} of Symbol => String) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String) + query_params = opts[:query_params] || {} of Symbol => String + form_params = opts[:form_params] || {} of Symbol => String + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :verbose => @config.debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update body: req_body + if @config.debugging + Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"} + end + end + request.headers = header_params + request.body = req_body + request.url url + request.params = query_params + download_file(request) if opts[:return_type] == "File" + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params["Content-Type"] == "application/x-www-form-urlencoded" + data = URI.encode_www_form(form_params) + elsif header_params["Content-Type"] == "multipart/form-data" + data = {} of Symbol => String + form_params.each do |key, value| + case value + when ::File, ::Tempfile + # TODO hardcode to application/octet-stream, need better way to detect content type + data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path) + when ::Array, nil + # let Faraday handle Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # TODO fix streaming response + #def download_file(request) + # @stream = [] + + # # handle streaming Responses + # request.options.on_data = Proc.new do |chunk, overall_received_bytes| + # @stream << chunk + # end + #end + end +end diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client_faraday_partial.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client_faraday_partial.mustache new file mode 100644 index 00000000000..dfef217e037 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_client_faraday_partial.mustache @@ -0,0 +1,138 @@ + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {} of Symbol => String) + ssl_options = { + :ca_file => @config.ssl_ca_file, + :verify => @config.ssl_verify, + :verify_mode => @config.ssl_verify_mode, + :client_cert => @config.ssl_client_cert, + :client_key => @config.ssl_client_key + } + + connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn| + conn.basic_auth(config.username, config.password) + if opts[:header_params]["Content-Type"] == "multipart/form-data" + conn.request :multipart + conn.request :url_encoded + end + conn.adapter(Faraday.default_adapter) + end + + begin + response = connection.public_send(http_method.to_sym.downcase) do |req| + build_request(http_method, path, req, opts) + end + + if @config.debugging + Log.debug {"HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"} + end + + unless response.success? + if response.status == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(code: 0, + message: response.return_message) + else + fail ApiError.new(code: response.status, + response_headers: response.headers, + response_body: response.body), + response.reason_phrase + end + end + rescue Faraday::TimeoutError + fail ApiError.new("Connection timed out") + end + + if opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.status, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, request, opts = {} of Symbol => String) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String) + query_params = opts[:query_params] || {} of Symbol => String + form_params = opts[:form_params] || {} of Symbol => String + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :verbose => @config.debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update body: req_body + if @config.debugging + Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"} + end + end + request.headers = header_params + request.body = req_body + request.url url + request.params = query_params + download_file(request) if opts[:return_type] == "File" + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params["Content-Type"] == "application/x-www-form-urlencoded" + data = URI.encode_www_form(form_params) + elsif header_params["Content-Type"] == "multipart/form-data" + data = {} of Symbol => String + form_params.each do |key, value| + case value + when ::File, ::Tempfile + # TODO hardcode to application/octet-stream, need better way to detect content type + data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path) + when ::Array, nil + # let Faraday handle Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + def download_file(request) + @stream = [] + + # handle streaming Responses + request.options.on_data = Proc.new do |chunk, overall_received_bytes| + @stream << chunk + end + end diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache new file mode 100644 index 00000000000..d8e95e77461 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache @@ -0,0 +1,153 @@ + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {} of Symbol => String) + request = build_request(http_method, path, opts) + response = request.run + + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.timed_out? + fail ApiError.new("Connection timed out") + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(code: 0, + message: response.return_message) + else + fail ApiError.new(code: response.code, + response_headers: response.headers, + response_body: response.body), + response.status_message + end + end + + if opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, opts = {} of Symbol => String) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {} of Symbol => String) + query_params = opts[:query_params] || {} of Symbol => String + form_params = opts[:form_params] || {} of Symbol => String + + {{#hasAuthMethods}} + update_params_for_auth! header_params, query_params, opts[:auth_names] + {{/hasAuthMethods}} + + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :verbose => @config.debugging + } + + # set custom cert, if provided + req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update body: req_body + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + request = Typhoeus::Request.new(url, req_opts) + download_file(request) if opts[:return_type] == "File" + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params["Content-Type"] == "application/x-www-form-urlencoded" || + header_params["Content-Type"] == "multipart/form-data" + data = {} of Symbol => String + form_params.each do |key, value| + case value + when ::File, ::Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # The response body is written to the file in chunks in order to handle files which + # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby + # process can use. + # + # @see Configuration#temp_folder_path + def download_file(request) + tempfile = nil + encoding = nil + request.on_headers do |response| + content_disposition = response.headers["Content-Disposition"] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=[""]?([^""\s]+)[""]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = "download-" + end + prefix = prefix + "-" unless prefix.end_with?("-") + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + @tempfile = tempfile + end + request.on_body do |chunk| + chunk.force_encoding(encoding) + tempfile.write(chunk) + end + request.on_complete do |response| + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + end + end + end diff --git a/modules/openapi-generator/src/main/resources/crystal/api_doc.mustache b/modules/openapi-generator/src/main/resources/crystal/api_doc.mustache new file mode 100644 index 00000000000..bdeeb568912 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_doc.mustache @@ -0,0 +1,118 @@ +# {{moduleName}}::{{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}}{{#returnTypeIsPrimitive}}{{returnType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}<{{{returnType}}}>{{/returnTypeIsPrimitive}} {{/returnType}}{{operationId}}{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}} + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Examples + +```ruby +require 'time' +require '{{{gemName}}}' +{{#hasAuthMethods}} +# setup authorization +{{{moduleName}}}.configure do |config|{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + # Configure HTTP basic authorization: {{{name}}} + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD'{{/isBasicBasic}}{{#isBasicBearer}} + # Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}} + config.access_token = 'YOUR_BEARER_TOKEN'{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + # Configure API key authorization: {{{name}}} + config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} + # Configure OAuth2 access token for authorization: {{{name}}} + config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} +{{/authMethods}}end +{{/hasAuthMethods}} + +api_instance = {{{moduleName}}}::{{{classname}}}.new +{{#requiredParams}} +{{{paramName}}} = {{{vendorExtensions.x-ruby-example}}} # {{{dataType}}} | {{{description}}} +{{/requiredParams}} +{{#optionalParams}} +{{#-first}} +opts = { +{{/-first}} + {{{paramName}}}: {{{vendorExtensions.x-ruby-example}}}{{^-last}},{{/-last}} # {{{dataType}}} | {{{description}}} +{{#-last}} +} +{{/-last}} +{{/optionalParams}} + +begin + {{#summary}}# {{{.}}}{{/summary}} + {{#returnType}}result = {{/returnType}}api_instance.{{{operationId}}}{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}} + {{#returnType}} + p result + {{/returnType}} +rescue {{{moduleName}}}::ApiError => e + puts "Error when calling {{classname}}->{{{operationId}}}: #{e}" +end +``` + +#### Using the {{operationId}}_with_http_info variant + +This returns an Array which contains the response data{{^returnType}} (`nil` in this case){{/returnType}}, status code and headers. + +> {{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Integer, Hash)> {{operationId}}_with_http_info{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}} + +```ruby +begin + {{#summary}}# {{{.}}}{{/summary}} + data, status_code, headers = api_instance.{{{operationId}}}_with_http_info{{#hasParams}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}){{/hasParams}} + p status_code # => 2xx + p headers # => { ... } + p data # => {{#returnType}}{{#returnTypeIsPrimitive}}{{returnType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}<{{{returnType}}}>{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}nil{{/returnType}} +rescue {{{moduleName}}}::ApiError => e + puts "Error when calling {{classname}}->{{{operationId}}}_with_http_info: #{e}" +end +``` + +### Parameters + +{{^allParams}} +This endpoint does not need any parameter. +{{/allParams}} +{{#allParams}} +{{#-first}} +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +{{/-first}} +| **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional]{{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}nil (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}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/crystal/api_error.mustache b/modules/openapi-generator/src/main/resources/crystal/api_error.mustache new file mode 100644 index 00000000000..fd39b5bef27 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_error.mustache @@ -0,0 +1,33 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +module {{moduleName}} + class ApiError < Exception + getter code : Int32? + getter response_headers : Hash(String, Array(String) | String)? + + # Usage examples: + # ApiError.new + # ApiError.new(message: "message") + # ApiError.new(code: 500, response_headers: {}, message: "") + # ApiError.new(code: 404, message: "Not Found") + def initialize(@code , @message, @response_headers) + end + + def initialize(@code , @message) + end + + # Override to_s to display a friendly error message + def to_s + msg = "" + msg = msg + "\nHTTP status code: #{code}" if @code + msg = msg + "\nResponse headers: #{response_headers}" if @response_headers + if @message.nil? || @message.empty? + msg = msg + "\nError message: the server returns an error but the HTTP respone body is empty." + else + msg = msg + "\nResponse body: #{@message}" + end + + msg + end + end +end diff --git a/modules/openapi-generator/src/main/resources/crystal/api_info.mustache b/modules/openapi-generator/src/main/resources/crystal/api_info.mustache new file mode 100644 index 00000000000..1b3f9cb5ac4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_info.mustache @@ -0,0 +1,12 @@ +{{#appName}} +#{{{appName}}} + +{{/appName}} +{{#appDescription}} +#{{{appDescription}}} + +{{/appDescription}} +{{#version}}The version of the OpenAPI document: {{version}}{{/version}} +{{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +Generated by: https://openapi-generator.tech +OpenAPI Generator version: {{{generatorVersion}}} diff --git a/modules/openapi-generator/src/main/resources/crystal/api_test.mustache b/modules/openapi-generator/src/main/resources/crystal/api_test.mustache new file mode 100644 index 00000000000..f4e0eb49e64 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/api_test.mustache @@ -0,0 +1,38 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for {{moduleName}}::{{classname}} +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +{{#operations}}describe "{{classname}}" do + describe "test an instance of {{classname}}" do + it "should create an instance of {{classname}}" do + api_instance = {{moduleName}}::{{classname}}.new + # TODO expect(api_instance).to be_instance_of({{moduleName}}::{{classname}}) + end + end + +{{#operation}} + # unit tests for {{operationId}} + {{#summary}} + # {{summary}} + {{/summary}} + {{#notes}} + # {{notes}} + {{/notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] + describe "{{operationId}} test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +{{/operation}} +end +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/crystal/base_object.mustache b/modules/openapi-generator/src/main/resources/crystal/base_object.mustache new file mode 100644 index 00000000000..c7abd09b36b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/base_object.mustache @@ -0,0 +1,120 @@ + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + {{#parent}} + super(attributes) + {{/parent}} + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = {{moduleName}}.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {{^parent}}{} of Symbol => String{{/parent}}{{#parent}}super{{/parent}} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache new file mode 100644 index 00000000000..a3a815fc042 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache @@ -0,0 +1,356 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "log" + +module {{moduleName}} + class Configuration + # Defines url scheme + property scheme : String + + # Defines url host + property host : String + + # Defines url base path + property base_path : String + + # Define server configuration index + property server_index : Int32 + + # Define server operation configuration index + property server_operation_index : Hash(Symbol, String) + + # Default server variables + property server_variables : Hash(Symbol, String) + + # Default server operation variables + property server_operation_variables : Hash(Symbol, String) + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key[:"api_key"] = "xxx" + property api_key : Hash(Symbol, String) + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix[:"api_key"] = "Token" + property api_key_prefix : Hash(Symbol, String) + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + property username : String? + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + property password : String? + + # Defines the access token (Bearer) used with OAuth2. + property access_token : String? + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + property debugging : Bool + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + property temp_folder_path : String? + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + property timeout : Int32 + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + property client_side_validation : Bool + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + #TODO attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + # TODO attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + # TODO attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + # TODO attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + # TODO attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to Nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + #property params_encoding : String? + + def initialize + @scheme = "{{scheme}}" + @host = "{{host}}{{#port}}:{{{.}}}{{/port}}" + @base_path = "{{contextPath}}" + @server_index = 0 + @server_operation_index = {} of Symbol => String + @server_variables = {} of Symbol => String + @server_operation_variables = {} of Symbol => String + @api_key = {} of Symbol => String + @api_key_prefix = {} of Symbol => String + @timeout = 0 + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + #@params_encoding = nil + #@cert_file = nil + #@key_file = nil + @debugging = false + @username = nil + @password = nil + @access_token = nil + @temp_folder_path = nil + + # TODO revise below to support block + #yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, "") + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, "").split("/").first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, "/") + @base_path = "" if @base_path == "/" + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = Nil) + # TODO revise below to support operation-level server setting + #index = server_operation_index.fetch(operation, server_index) + return "#{scheme}://#{[host, base_path].join("/").gsub(/\/+/, "/")}".sub(/\/+\z/, "") #if index == Nil + + #server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + "Basic " + ["#{username}:#{password}"].pack("m").delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + Hash{ {{#authMethods}}{{#isApiKey}}"{{name}}" => { + type: "api_key", + in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, + key: "{{keyParamName}}", + value: api_key_with_prefix("{{keyParamName}}") + }, +{{/isApiKey}} +{{#isBasic}} +{{#isBasicBasic}} + "{{name}}" => + { + type: "basic", + in: "header", + key: "Authorization", + value: basic_auth_token + }, +{{/isBasicBasic}} +{{#isBasicBearer}} + "{{name}}" => + { + type: "bearer", + in: "header", + {{#bearerFormat}} + format: "{{{.}}}", + {{/bearerFormat}} + key: "Authorization", + value: "Bearer #{access_token}" + }, +{{/isBasicBearer}} +{{/isBasic}} +{{#isOAuth}} + "{{name}}" => + { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, +{{/isOAuth}} +{{/authMethods}} + } + end + + # Returns an array of Server setting + def server_settings + [ + {{#servers}} + { + url: "{{{url}}}", + description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + variables: { + {{/-first}} + {{{name}}}: { + description: "{{{description}}}{{^description}}No description provided{{/description}}", + default_value: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + enum_values: [ + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + }{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/variables}} + }{{^-last}},{{/-last}} + {{/servers}} + ] + end + + def operation_server_settings + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + { + "{{{classname}}}.{{{nickname}}}": [ + {{/-first}} + { + url: "{{{url}}}", + description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + variables: { + {{/-first}} + {{{name}}}: { + description: "{{{description}}}{{^description}}No description provided{{/description}}", + default_value: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + enum_values: [ + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + }{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/variables}} + }{{^-last}},{{/-last}} + {{#-last}} + ], + } + {{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {} of Symbol => String, servers = Nil) + servers = server_settings if servers == Nil + + # check array index out of bound + if (index < 0 || index >= servers.size) + raise ArgumentError.new("Invalid index #{index} when selecting the server. Must be less than #{servers.size}") + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + raise ArgumentError.new("The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}.") + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + end +end diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration_spec.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration_spec.mustache new file mode 100644 index 00000000000..22a113e8e32 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/configuration_spec.mustache @@ -0,0 +1,34 @@ +=begin +{{> api_info}} +=end + +require 'spec_helper' + +describe {{moduleName}}::Configuration do + let(:config) { {{moduleName}}::Configuration.default } + + before(:each) do + # uncomment below to setup host and base_path + # require 'URI' + # uri = URI.parse("{{{basePath}}}") + # {{moduleName}}.configure do |c| + # c.host = uri.host + # c.base_path = uri.path + # end + end + + describe '#base_url' do + it 'should have the default value' do + # uncomment below to test default value of the base path + # expect(config.base_url).to eq("{{{basePath}}}") + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + # uncomment below to test trailing slashes + # expect(config.base_url).to eq("{{{basePath}}}") + end + end + end +end diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration_tls_faraday_partial.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration_tls_faraday_partial.mustache new file mode 100644 index 00000000000..c35c988f933 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/configuration_tls_faraday_partial.mustache @@ -0,0 +1,29 @@ + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + #TODO attr_accessor :ssl_verify + + ### TLS/SSL setting + # Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html) + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + #TODO attr_accessor :ssl_verify_mode + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + #TODO attr_accessor :ssl_ca_file + + ### TLS/SSL setting + # Client certificate file (for client certificate) + #TODO attr_accessor :ssl_client_cert + + ### TLS/SSL setting + # Client private key file (for client certificate) + #TODO attr_accessor :ssl_client_key diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration_tls_typhoeus_partial.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration_tls_typhoeus_partial.mustache new file mode 100644 index 00000000000..1ab1b2d0307 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/configuration_tls_typhoeus_partial.mustache @@ -0,0 +1,34 @@ + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + #TODO attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + # TODO attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + # TODO attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + # TODO attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + # TODO attr_accessor :key_file diff --git a/modules/openapi-generator/src/main/resources/crystal/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/crystal/git_push.sh.mustache new file mode 100755 index 00000000000..8b3f689c912 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/git_push.sh.mustache @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/openapi-generator/src/main/resources/crystal/gitignore.mustache b/modules/openapi-generator/src/main/resources/crystal/gitignore.mustache new file mode 100644 index 00000000000..05a17cb8f0a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/gitignore.mustache @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/modules/openapi-generator/src/main/resources/crystal/model.mustache b/modules/openapi-generator/src/main/resources/crystal/model.mustache new file mode 100644 index 00000000000..a19cc5f3f6a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/model.mustache @@ -0,0 +1,23 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "time" + +module {{moduleName}} +{{#models}} +{{#model}} +{{#isEnum}} +{{>partial_model_enum_class}} +{{/isEnum}} +{{^isEnum}} +{{#oneOf}} +{{#-first}} +{{>partial_oneof_module}} +{{/-first}} +{{/oneOf}} +{{^oneOf}} +{{>partial_model_generic}} +{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} +end diff --git a/modules/openapi-generator/src/main/resources/crystal/model_doc.mustache b/modules/openapi-generator/src/main/resources/crystal/model_doc.mustache new file mode 100644 index 00000000000..37809685d1c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/model_doc.mustache @@ -0,0 +1,12 @@ +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +{{>partial_oneof_module_doc}} +{{/-first}} +{{/oneOf}} +{{^oneOf}} +{{>partial_model_generic_doc}} +{{/oneOf}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/crystal/model_test.mustache b/modules/openapi-generator/src/main/resources/crystal/model_test.mustache new file mode 100644 index 00000000000..3cc572b5878 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/model_test.mustache @@ -0,0 +1,75 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for {{moduleName}}::{{classname}} +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +{{#models}} +{{#model}} +describe {{moduleName}}::{{classname}} do +{{^oneOf}} + + describe "test an instance of {{classname}}" do + it "should create an instance of {{classname}}" do + #instance = {{moduleName}}::{{classname}}.new + #expect(instance).to be_instance_of({{moduleName}}::{{classname}}) + end + end +{{#vars}} + describe "test attribute '{{{name}}}'" do + it "should work" do + {{#isEnum}} + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + # validator = Petstore::EnumTest::EnumAttributeValidator.new("{{{dataType}}}", [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]) + # validator.allowable_values.each do |value| + # expect { instance.{{name}} = value }.not_to raise_error + # end + {{/isEnum}} + {{^isEnum}} + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + {{/isEnum}} + end + end + +{{/vars}} +{{/oneOf}} +{{#oneOf}} +{{#-first}} + describe ".openapi_one_of" do + it "lists the items referenced in the oneOf array" do + expect(described_class.openapi_one_of).to_not be_empty + end + end + + {{#discriminator}} + {{#propertyName}} + describe ".openapi_discriminator_name" do + it "returns the value of the "discriminator" property" do + expect(described_class.openapi_discriminator_name).to_not be_empty + end + end + + {{/propertyName}} + {{#mappedModels}} + {{#-first}} + describe ".openapi_discriminator_mapping" do + it "returns the key/values of the "mapping" property" do + expect(described_class.openapi_discriminator_mapping.values.sort).to eq(described_class.openapi_one_of.sort) + end + end + + {{/-first}} + {{/mappedModels}} + {{/discriminator}} + describe ".build" do + it "returns the correct model" do + end + end +{{/-first}} +{{/oneOf}} +end +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache new file mode 100644 index 00000000000..4b8b5a0ffda --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache @@ -0,0 +1,20 @@ + class {{classname}}{{#allowableValues}}{{#enumVars}} + {{{name}}} = {{{value}}}.freeze{{/enumVars}} + +{{/allowableValues}} + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + constantValues = {{classname}}.constants.select { |c| {{classname}}::const_get(c) == value } + raise "Invalid ENUM value #{value} for class #{{{classname}}}" if constantValues.empty? + value + end + end \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache new file mode 100644 index 00000000000..18f00b1d529 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache @@ -0,0 +1,296 @@ + {{#description}} + # {{{description}}} + {{/description}} + class {{classname}}{{#parent}} < {{{.}}}{{/parent}} include JSON::Serializable + include JSON::Serializable {{#vars}} + {{#description}} + # {{{description}}} + {{/description}} + @[JSON::Field(key: {{{baseName}}}, type: {{{dataType}}}{{#default}}, default: {{{.}}}{{/default}}{{#isNullable}}, nilable: true, emit_null: true{{/isNullable}})] + property {{{name}}} : {{{dataType}}} + + {{/vars}} +{{#hasEnums}} + class EnumAttributeValidator + getter datatype : String + getter allowable_values : Array(String) + + def initialize(datatype, allowable_values) + @datatype = datatype + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + +{{/hasEnums}} + {{#anyOf}} + {{#-first}} + # List of class defined in anyOf (OpenAPI v3) + def self.openapi_any_of + [ + {{/-first}} + :"{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + end + + {{/-last}} + {{/anyOf}} + {{#allOf}} + {{#-first}} + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + {{/-first}} + :"{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + end + + {{/-last}} + {{/allOf}} + {{#discriminator}} + {{#propertyName}} + # discriminator's property name in OpenAPI v3 + def self.openapi_discriminator_name + :"{{{.}}}" + end + + {{/propertyName}} + {{/discriminator}} + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize({{#vars}}@{{{name}}} : {{{dataType}}}{{^required}} | Nil{{/required}}{{^-last}}, {{/-last}}{{/vars}}) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = {{^parent}}Array.new{{/parent}}{{#parent}}super{{/parent}} + {{#vars}} + {{^isNullable}} + {{#required}} + if @{{{name}}}.nil? + invalid_properties.push("invalid value for \"{{{name}}}\", {{{name}}} cannot be nil.") + end + + {{/required}} + {{/isNullable}} + {{#hasValidation}} + {{#maxLength}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} + invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.") + end + + {{/maxLength}} + {{#minLength}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} + invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.") + end + + {{/minLength}} + {{#maximum}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + invalid_properties.push("invalid value for \"{{{name}}}\", must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.") + end + + {{/maximum}} + {{#minimum}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + invalid_properties.push("invalid value for \"{{{name}}}\", must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.") + end + + {{/minimum}} + {{#pattern}} + pattern = Regexp.new({{{pattern}}}) + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ pattern + invalid_properties.push("invalid value for \"{{{name}}}\", must conform to the pattern #{pattern}.") + end + + {{/pattern}} + {{#maxItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}." + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}." + end + + {{/minItems}} + {{/hasValidation}} + {{/vars}} + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + {{#vars}} + {{^isNullable}} + {{#required}} + return false if @{{{name}}}.nil? + {{/required}} + {{/isNullable}} + {{#isEnum}} + {{^isContainer}} + {{{name}}}_validator = EnumAttributeValidator.new("{{{dataType}}}", [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]) + return false unless {{{name}}}_validator.valid?(@{{{name}}}) + {{/isContainer}} + {{/isEnum}} + {{#hasValidation}} + {{#maxLength}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} + {{/maxLength}} + {{#minLength}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} + {{/minLength}} + {{#maximum}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + {{/maximum}} + {{#minimum}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + {{/minimum}} + {{#pattern}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) + {{/pattern}} + {{#maxItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + {{/maxItems}} + {{#minItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + {{/minItems}} + {{/hasValidation}} + {{/vars}} + {{#anyOf}} + {{#-first}} + _any_of_found = false + self.class.openapi_any_of.each do |_class| + _any_of = {{moduleName}}.const_get(_class).build_from_hash(self.to_hash) + if _any_of.valid? + _any_of_found = true + end + end + + if !_any_of_found + return false + end + + {{/-first}} + {{/anyOf}} + true{{#parent}} && super{{/parent}} + end + + {{#vars}} + {{#isEnum}} + {{^isContainer}} + # Custom attribute writer method checking allowed values (enum). + # @param [Object] {{{name}}} Object to be assigned + def {{{name}}}=({{{name}}}) + validator = EnumAttributeValidator.new("{{{dataType}}}", [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]) + unless validator.valid?({{{name}}}) + raise ArgumentError.new("invalid value for \"{{{name}}}\", must be one of #{validator.allowable_values}.") + end + @{{{name}}} = {{{name}}} + end + + {{/isContainer}} + {{/isEnum}} + {{^isEnum}} + {{#hasValidation}} + # Custom attribute writer method with validation + # @param [Object] {{{name}}} Value to be assigned + def {{{name}}}=({{{name}}}) + {{^isNullable}} + {{#required}} + if {{{name}}}.nil? + raise ArgumentError.new("{{{name}}} cannot be nil") + end + + {{/required}} + {{/isNullable}} + {{#maxLength}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length > {{{maxLength}}} + raise ArgumentError.new("invalid value for "{{{name}}}", the character length must be smaller than or equal to {{{maxLength}}}.") + end + + {{/maxLength}} + {{#minLength}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length < {{{minLength}}} + raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.") + end + + {{/minLength}} + {{#maximum}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + raise ArgumentError.new("invalid value for \"{{{name}}}\", must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.") + end + + {{/maximum}} + {{#minimum}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + raise ArgumentError.new("invalid value for \"{{{name}}}\", must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.") + end + + {{/minimum}} + {{#pattern}} + pattern = Regexp.new({{{pattern}}}) + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} !~ pattern + raise ArgumentError.new("invalid value for \"{{{name}}}\", must conform to the pattern #{pattern}.") + end + + {{/pattern}} + {{#maxItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length > {{{maxItems}}} + raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}.") + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length < {{{minItems}}} + raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}.") + end + + {{/minItems}} + @{{{name}}} = {{{name}}} + end + + {{/hasValidation}} + {{/isEnum}} + {{/vars}} + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class{{#vars}} && + {{name}} == o.{{name}}{{/vars}}{{#parent}} && super(o){{/parent}} + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [{{#vars}}{{name}}{{^-last}}, {{/-last}}{{/vars}}].hash + end + +{{> base_object}} + end diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic_doc.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic_doc.mustache new file mode 100644 index 00000000000..f188dd23e6e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic_doc.mustache @@ -0,0 +1,28 @@ +# {{moduleName}}::{{classname}} + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +{{#vars}} +| **{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional]{{/required}}{{#isReadOnly}}[readonly]{{/isReadOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} | +{{/vars}} + +## Example + +```ruby +require '{{{gemName}}}' + +{{^vars}} +instance = {{moduleName}}::{{classname}}.new() +{{/vars}} +{{#vars}} +{{#-first}} +instance = {{moduleName}}::{{classname}}.new( +{{/-first}} + {{name}}: {{example}}{{^-last}},{{/-last}} +{{#-last}} +) +{{/-last}} +{{/vars}} +``` diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module.mustache new file mode 100644 index 00000000000..14dc1635bb7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module.mustache @@ -0,0 +1,137 @@ + {{#description}} + # {{{description}}} + {{/description}} + module {{classname}} + class << self + {{#oneOf}} + {{#-first}} + # List of class defined in oneOf (OpenAPI v3) + def openapi_one_of + [ + {{/-first}} + :'{{{.}}}'{{^-last}},{{/-last}} + {{#-last}} + ] + end + + {{/-last}} + {{/oneOf}} + {{#discriminator}} + {{#propertyName}} + # Discriminator's property name (OpenAPI v3) + def openapi_discriminator_name + :'{{{.}}}' + end + + {{/propertyName}} + {{#mappedModels}} + {{#-first}} + # Discriminator's mapping (OpenAPI v3) + def openapi_discriminator_mapping + { + {{/-first}} + :'{{{mappingName}}}' => :'{{{modelName}}}'{{^-last}},{{/-last}} + {{#-last}} + } + end + + {{/-last}} + {{/mappedModels}} + {{/discriminator}} + # Builds the object + # @param [Mixed] Data to be matched against the list of oneOf items + # @return [Object] Returns the model or the data itself + def build(data) + {{#discriminator}} + discriminator_value = data[openapi_discriminator_name] + return nil unless discriminator_value + {{#mappedModels}} + {{#-first}} + + klass = openapi_discriminator_mapping[discriminator_value.to_sym] + return nil unless klass + + {{moduleName}}.const_get(klass).build_from_hash(data) + {{/-first}} + {{/mappedModels}} + {{^mappedModels}} + {{moduleName}}.const_get(discriminator_value).build_from_hash(data) + {{/mappedModels}} + {{/discriminator}} + {{^discriminator}} + # Go through the list of oneOf items and attempt to identify the appropriate one. + # Note: + # - We do not attempt to check whether exactly one item matches. + # - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 }) + # due to the way the deserialization is made in the base_object template (it just casts without verifying). + # - TODO: scalar values are defacto behaving as if they were nullable. + # - TODO: logging when debugging is set. + openapi_one_of.each do |klass| + begin + next if klass == :AnyType # "nullable: true" + typed_data = find_and_cast_into_type(klass, data) + return typed_data if typed_data + rescue # rescue all errors so we keep iterating even if the current item lookup raises + end + end + + openapi_one_of.include?(:AnyType) ? data : nil + {{/discriminator}} + end + {{^discriminator}} + + private + + SchemaMismatchError = Class.new(StandardError) + + # Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse. + def find_and_cast_into_type(klass, data) + return if data.nil? + + case klass.to_s + when 'Boolean' + return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass) + when 'Float' + return data if data.instance_of?(Float) + when 'Integer' + return data if data.instance_of?(Integer) + when 'Time' + return Time.parse(data) + when 'Date' + return Date.parse(data) + when 'String' + return data if data.instance_of?(String) + when 'Object' # "type: object" + return data if data.instance_of?(Hash) + when /\AArray<(?.+)>\z/ # "type: array" + if data.instance_of?(Array) + sub_type = Regexp.last_match[:sub_type] + return data.map { |item| find_and_cast_into_type(sub_type, item) } + end + when /\AHash.+)>\z/ # "type: object" with "additionalProperties: { ... }" + if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) } + sub_type = Regexp.last_match[:sub_type] + return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) } + end + else # model + const = {{moduleName}}.const_get(klass) + if const + if const.respond_to?(:openapi_one_of) # nested oneOf model + model = const.build(data) + return model if model + else + # raise if data contains keys that are not known to the model + raise unless (data.keys - const.acceptable_attributes).empty? + model = const.build_from_hash(data) + return model if model && model.valid? + end + end + end + + raise # if no match by now, raise + rescue + raise SchemaMismatchError, "#{data} doesn't match the #{klass} type" + end + {{/discriminator}} + end + end diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module_doc.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module_doc.mustache new file mode 100644 index 00000000000..64a6c32dc85 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/partial_oneof_module_doc.mustache @@ -0,0 +1,92 @@ +# {{moduleName}}::{{classname}} + +## Class instance methods + +### `openapi_one_of` + +Returns the list of classes defined in oneOf. + +#### Example + +```ruby +require '{{{gemName}}}' + +{{moduleName}}::{{classname}}.openapi_one_of +# => +{{#oneOf}} +{{#-first}} +# [ +{{/-first}} +# :'{{{.}}}'{{^-last}},{{/-last}} +{{#-last}} +# ] +{{/-last}} +{{/oneOf}} +``` +{{#discriminator}} +{{#propertyName}} + +### `openapi_discriminator_name` + +Returns the discriminator's property name. + +#### Example + +```ruby +require '{{{gemName}}}' + +{{moduleName}}::{{classname}}.openapi_discriminator_name +# => :'{{{.}}}' +``` +{{/propertyName}} +{{#mappedModels}} +{{#-first}} + +### `openapi_discriminator_name` + +Returns the discriminator's mapping. + +#### Example + +```ruby +require '{{{gemName}}}' + +{{moduleName}}::{{classname}}.openapi_discriminator_mapping +# => +# { +{{/-first}} +# :'{{{mappingName}}}' => :'{{{modelName}}}'{{^-last}},{{/-last}} +{{#-last}} +# } +{{/-last}} +{{/mappedModels}} +{{/discriminator}} + +### build + +Find the appropriate object from the `openapi_one_of` list and casts the data into it. + +#### Example + +```ruby +require '{{{gemName}}}' + +{{moduleName}}::{{classname}}.build(data) +# => {{#oneOf}}{{#-first}}#<{{{.}}}:0x00007fdd4aab02a0>{{/-first}}{{/oneOf}} + +{{moduleName}}::{{classname}}.build(data_that_doesnt_match) +# => nil +``` + +#### Parameters + +| Name | Type | Description | +| ---- | ---- | ----------- | +| **data** | **Mixed** | data to be matched against the list of oneOf items | + +#### Return type + +{{#oneOf}} +- `{{{.}}}` +{{/oneOf}} +- `nil` (if no type matches) diff --git a/modules/openapi-generator/src/main/resources/crystal/rspec.mustache b/modules/openapi-generator/src/main/resources/crystal/rspec.mustache new file mode 100644 index 00000000000..83e16f80447 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/rspec.mustache @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/modules/openapi-generator/src/main/resources/crystal/rubocop.mustache b/modules/openapi-generator/src/main/resources/crystal/rubocop.mustache new file mode 100644 index 00000000000..d32b2b1cdab --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/rubocop.mustache @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/modules/openapi-generator/src/main/resources/crystal/shard.mustache b/modules/openapi-generator/src/main/resources/crystal/shard.mustache new file mode 100644 index 00000000000..89376ca4593 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/shard.mustache @@ -0,0 +1,20 @@ +name: {{{moduleName}}} +version: {{{shardVersion}}} +authors: + - {{{shardAuthors}}} +description: | + - {{{ shardDescription}}} +crystal: ">= 0.35.1" +dependencies: + crest: + github: mamantoha/crest + version: ~> 0.26.0 + +development_dependencies: + kemal: + github: kemalcr/kemal + version: ~>0.27.0 + ameba: + github: crystal-ameba/ameba + +license: {{{shardLicense}}} diff --git a/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache new file mode 100644 index 00000000000..7e3e9b162d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache @@ -0,0 +1,27 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +# Dependencies +require "crest" +require "log" + +module {{moduleName}} + Log = ::Log.for("{{moduleName}}") # => Log for {{moduleName}} source + + VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + + # Customize default settings for the SDK using block. + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end +end + +require "./{{shardName}}/**" diff --git a/modules/openapi-generator/src/main/resources/crystal/spec_helper.mustache b/modules/openapi-generator/src/main/resources/crystal/spec_helper.mustache new file mode 100644 index 00000000000..9facafa4a93 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/spec_helper.mustache @@ -0,0 +1,6 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +# load modules +require "spec" +require "json" +require "../src/{{{shardName}}}" \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/crystal/travis.mustache b/modules/openapi-generator/src/main/resources/crystal/travis.mustache new file mode 100644 index 00000000000..21509cfe82a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/travis.mustache @@ -0,0 +1,8 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +language: crystal + +script: + - crystal spec +# uncomment below to check the code format +# - crystal tool format --check diff --git a/modules/openapi-generator/src/main/resources/crystal/version.mustache b/modules/openapi-generator/src/main/resources/crystal/version.mustache new file mode 100644 index 00000000000..9be1d633971 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/crystal/version.mustache @@ -0,0 +1,5 @@ +# {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} + +module {{moduleName}} + VERSION = '{{shardVersion}}' +end diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache index 504b5a22439..c1d025d7f03 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache @@ -65,10 +65,10 @@ namespace {{packageName}}.Client /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is {{{packageName}}}.Model.AbstractOpenAPISchema) + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return (({{{packageName}}}.Model.AbstractOpenAPISchema)obj).ToJson(); + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); } else { @@ -576,7 +576,7 @@ namespace {{packageName}}.Client } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof({{{packageName}}}.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { T instance = (T)Activator.CreateInstance(typeof(T)); MethodInfo method = typeof(T).GetMethod("FromJson"); diff --git a/modules/openapi-generator/src/main/resources/dart-dio/analysis_options.mustache b/modules/openapi-generator/src/main/resources/dart-dio/analysis_options.mustache index 655cb67bd88..a611887d3ac 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/analysis_options.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/analysis_options.mustache @@ -1 +1,9 @@ -analyzer: \ No newline at end of file +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache index a7f830a5135..ee4b9a0579c 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache @@ -1,3 +1,4 @@ +{{>header}} import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -31,8 +32,8 @@ class {{classname}} { }) async { final String _path = '{{{path}}}'{{#pathParams}}.replaceAll('{' r'{{baseName}}' '}', {{{paramName}}}.toString()){{/pathParams}}; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; @@ -43,15 +44,15 @@ class {{classname}} { {{#queryParams}} queryParams[r'{{baseName}}'] = {{paramName}}; {{/queryParams}} - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [{{^hasConsumes}}];{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} + final contentTypes = [{{^hasConsumes}}];{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} '{{{mediaType}}}',{{/consumes}} ];{{/hasConsumes}} {{#hasFormParams}} - final Map formData = {}; + final formData = {}; {{#isMultipart}} {{#formParams}} {{^isFile}} @@ -76,18 +77,30 @@ class {{classname}} { {{/hasFormParams}} {{#bodyParam}} - {{#isArray}} + {{#isContainer}} + {{#isArray}} const type = FullType(BuiltList, [FullType({{baseType}})]); final serializedBody = _serializers.serialize({{paramName}}, specifiedType: type); - {{/isArray}} - {{^isArray}} - final serializedBody = _serializers.serialize({{paramName}}); - {{/isArray}} + {{/isArray}} + {{#isMap}} + const type = FullType(BuiltMap, [FullType(String), FullType({{baseType}})]); + final serializedBody = _serializers.serialize({{paramName}}, specifiedType: type); + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} + var serializedBody = {{paramName}}; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + final bodySerializer = _serializers.serializerForType({{{baseType}}}) as Serializer<{{{baseType}}}>; + final serializedBody = _serializers.serializeWith(bodySerializer, {{paramName}}); + {{/isPrimitiveType}} + {{/isContainer}} final json{{paramName}} = json.encode(serializedBody); bodyData = json{{paramName}}; {{/bodyParam}} - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, @@ -97,8 +110,8 @@ class {{classname}} { responseType: ResponseType.bytes, {{/isResponseFile}} headers: headerParams, - extra: { - 'secure': [{{^hasAuthMethods}}],{{/hasAuthMethods}}{{#hasAuthMethods}} + extra: { + 'secure': >[{{^hasAuthMethods}}],{{/hasAuthMethods}}{{#hasAuthMethods}} {{#authMethods}}{ 'type': '{{type}}', 'name': '{{name}}',{{#isApiKey}} @@ -124,14 +137,22 @@ class {{classname}} { final data = response.data as {{{returnType}}}; {{/returnTypeIsPrimitive}} {{^returnTypeIsPrimitive}} - final serializer = _serializers.serializerForType({{{returnType}}}); - final data = _serializers.deserializeWith<{{{returnType}}}>(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType({{{returnType}}}) as Serializer<{{{returnType}}}>; + final data = _serializers.deserializeWith<{{{returnType}}}>( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); {{/returnTypeIsPrimitive}} {{/returnSimpleType}} {{^returnSimpleType}} const collectionType = {{#isMap}}BuiltMap{{/isMap}}{{^isMap}}BuiltList{{/isMap}}; const type = FullType(collectionType, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{returnBaseType}}})]); - final {{{returnType}}} data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as {{{returnType}}}; {{/returnSimpleType}} {{/isResponseFile}} diff --git a/modules/openapi-generator/src/main/resources/dart-dio/api_util.mustache b/modules/openapi-generator/src/main/resources/dart-dio/api_util.mustache index e99530f6c39..c25fc859c05 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/api_util.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/api_util.mustache @@ -1,3 +1,4 @@ +{{>header}} import 'dart:convert'; import 'package:built_value/serializer.dart'; diff --git a/modules/openapi-generator/src/main/resources/dart-dio/apilib.mustache b/modules/openapi-generator/src/main/resources/dart-dio/apilib.mustache index 1ad200a5a7b..645a5fe7877 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/apilib.mustache @@ -1,3 +1,4 @@ +{{>header}} library {{pubName}}.api; import 'package:dio/dio.dart'; diff --git a/modules/openapi-generator/src/main/resources/dart-dio/auth/api_key_auth.mustache b/modules/openapi-generator/src/main/resources/dart-dio/auth/api_key_auth.mustache index dac23a9fcbc..f5dd98b6b09 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/auth/api_key_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/auth/api_key_auth.mustache @@ -1,3 +1,4 @@ +{{>header}} import 'dart:async'; import 'package:{{pubName}}/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +7,12 @@ class ApiKeyAuthInterceptor extends AuthInterceptor { Map apiKeys = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "apiKey"); - for (var info in authInfo) { - final authName = info["name"]; - final authKeyName = info["keyName"]; - final authWhere = info["where"]; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; final apiKey = apiKeys[authName]; if (apiKey != null) { if (authWhere == 'query') { diff --git a/modules/openapi-generator/src/main/resources/dart-dio/auth/auth.mustache b/modules/openapi-generator/src/main/resources/dart-dio/auth/auth.mustache index 703127c762b..e6dbe70849d 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/auth/auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/auth/auth.mustache @@ -1,5 +1,4 @@ -import 'dart:async'; - +{{>header}} import 'package:dio/dio.dart'; abstract class AuthInterceptor extends Interceptor { @@ -8,11 +7,11 @@ abstract class AuthInterceptor extends Interceptor { * Can return null if type is not present on auth data or if route doesn't need authentication */ List> getAuthInfo(RequestOptions route, String type) { - if (route.extra.containsKey("secure")) { - final auth = route.extra["secure"]; - List> results = []; - for (var info in auth) { - if(info["type"] == type) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + final results = >[]; + for (final info in auth) { + if (info['type'] == type) { results.add(info); } } diff --git a/modules/openapi-generator/src/main/resources/dart-dio/auth/basic_auth.mustache b/modules/openapi-generator/src/main/resources/dart-dio/auth/basic_auth.mustache index bcf4b50f59e..cd5faa2dbdd 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/auth/basic_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/auth/basic_auth.mustache @@ -1,3 +1,4 @@ +{{>header}} import 'dart:async'; import 'dart:convert'; import 'package:{{pubName}}/auth/auth.dart'; @@ -14,13 +15,13 @@ class BasicAuthInterceptor extends AuthInterceptor { Map authInfo = {}; @override - Future onRequest(RequestOptions options) { + Future onRequest(RequestOptions options) { final metadataAuthInfo = getAuthInfo(options, 'basic'); - for (var info in metadataAuthInfo) { - final authName = info['name']; + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; final basicAuthInfo = authInfo[authName]; - if(basicAuthInfo != null) { - String basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); + if (basicAuthInfo != null) { + final basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); options.headers['Authorization'] = basicAuth; break; } diff --git a/modules/openapi-generator/src/main/resources/dart-dio/auth/oauth.mustache b/modules/openapi-generator/src/main/resources/dart-dio/auth/oauth.mustache index 282428297a8..d70e7bb380f 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/auth/oauth.mustache @@ -1,3 +1,4 @@ +{{>header}} import 'dart:async'; import 'package:{{pubName}}/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +7,12 @@ class OAuthInterceptor extends AuthInterceptor { Map tokens = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "oauth"); - for (var info in authInfo) { - final token = tokens[info["name"]]; - if(token != null) { - options.headers["Authorization"] = "Bearer ${token}"; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'oauth'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; break; } } diff --git a/modules/openapi-generator/src/main/resources/dart-dio/class.mustache b/modules/openapi-generator/src/main/resources/dart-dio/class.mustache index 37499b5a822..aef4915cc0b 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/class.mustache @@ -25,7 +25,7 @@ abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builde static void _initializeBuilder({{{classname}}}Builder b) => b{{#vars}}{{#defaultValue}} ..{{{name}}} = {{#isEnum}}{{^isContainer}}const {{{classname}}}{{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/vars}}; - factory {{classname}}([updates({{classname}}Builder b)]) = _${{classname}}; + factory {{classname}}([void updates({{classname}}Builder b)]) = _${{classname}}; static Serializer<{{classname}}> get serializer => _${{#lambda.camelcase}}{{{classname}}}{{/lambda.camelcase}}Serializer; } {{! diff --git a/modules/openapi-generator/src/main/resources/dart-dio/header.mustache b/modules/openapi-generator/src/main/resources/dart-dio/header.mustache new file mode 100644 index 00000000000..2c023d48899 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart-dio/header.mustache @@ -0,0 +1,6 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import 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 index 21b52dc2bc2..31440035f4a 100644 --- 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 @@ -1,3 +1,4 @@ +{{>header}} import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'package:time_machine/time_machine.dart'; diff --git a/modules/openapi-generator/src/main/resources/dart-dio/model.mustache b/modules/openapi-generator/src/main/resources/dart-dio/model.mustache index b696da9cdb4..5fdbb1b77c8 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/model.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/model.mustache @@ -1,3 +1,4 @@ +{{>header}} {{#models}} {{#model}} {{#imports}} 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 c7e8bfd75f7..aefe59a62e5 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache @@ -2,7 +2,7 @@ name: {{pubName}} version: {{pubVersion}} description: {{pubDescription}} environment: - sdk: ">=2.3.0 <3.0.0" + sdk: ">=2.6.0 <3.0.0" dependencies: dio: ^3.0.9 built_value: ^7.1.0 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 16998d739db..eb73bd7453a 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache @@ -1,3 +1,4 @@ +{{>header}} library serializers; import 'package:built_value/iso_8601_date_time_serializer.dart'; @@ -9,25 +10,26 @@ import 'package:built_value/standard_json_plugin.dart'; import 'package:{{pubName}}/local_date_serializer.dart';{{/timeMachine}} {{#models}}{{#model}}import 'package:{{pubName}}/model/{{classFilename}}.dart'; {{/model}}{{/models}} - part 'serializers.g.dart'; -@SerializersFor(const [ -{{#models}}{{#model}}{{classname}}, -{{/model}}{{/models}} +@SerializersFor(const [{{#models}}{{#model}} + {{classname}},{{/model}}{{/models}} ]) - -//allow all models to be serialized within a list -Serializers serializers = (_$serializers.toBuilder() -{{#models}}{{#model}}..addBuilderFactory( -const FullType(BuiltList, const [const FullType({{classname}})]), -() => new ListBuilder<{{classname}}>()) -{{/model}}{{/models}} -..add(Iso8601DateTimeSerializer()) -).build(); +Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#serializers}} + ..addBuilderFactory( +{{#isArray}} + const FullType(BuiltList, [FullType({{baseType}})]), + () => ListBuilder<{{baseType}}>(), +{{/isArray}} +{{#isMap}} + const FullType(BuiltMap, [FullType(String), FullType({{baseType}})]), + () => MapBuilder(), +{{/isMap}} + ){{/serializers}}{{/apis}}{{/apiInfo}}{{#timeMachine}} + ..add(OffsetDateSerializer()) + ..add(OffsetDateTimeSerializer()){{/timeMachine}} + ..add(Iso8601DateTimeSerializer())) + .build(); Serializers standardSerializers = -(serializers.toBuilder() -{{#timeMachine}}..add(OffsetDateSerializer()) -..add(OffsetDateTimeSerializer()) -{{/timeMachine}}..addPlugin(StandardJsonPlugin())).build(); + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/modules/openapi-generator/src/main/resources/elm/operation.mustache b/modules/openapi-generator/src/main/resources/elm/operation.mustache index 0f4035a8188..de4d54d1798 100644 --- a/modules/openapi-generator/src/main/resources/elm/operation.mustache +++ b/modules/openapi-generator/src/main/resources/elm/operation.mustache @@ -33,7 +33,7 @@ import Uuid exposing (Uuid){{/includeUuid}} {-| {{{notes}}} -} {{/notes}} -{{operationId}} : {{#allParams}}{{^required}}Maybe {{/required}}{{#isArray}}List {{/isArray}}{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{#isModel}}Api.Data.{{/isModel}}{{dataType}}{{/datatypeWithEnum}} -> {{/allParams}}{{#authMethods}}{{#isBasicBearer}}String -> {{/isBasicBearer}}{{/authMethods}}Api.Request {{^responses}}(){{/responses}}{{#responses}}{{#is2xx}}{{^dataType}}(){{/dataType}}{{#isMap}}(Dict.Dict String {{/isMap}}{{#isArray}}(List {{/isArray}}{{^primitiveType}}{{^isUuid}}Api.Data.{{/isUuid}}{{/primitiveType}}{{#items}}{{#isModel}}Api.Data.{{/isModel}}{{/items}}{{dataType}}{{#isArray}}){{/isArray}}{{#isMap}}){{/isMap}}{{/is2xx}}{{/responses}} +{{operationId}} : {{#allParams}}{{^required}}Maybe {{/required}}{{#isArray}}List {{/isArray}}{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{#isModel}}Api.Data.{{/isModel}}{{dataType}}{{/datatypeWithEnum}} -> {{/allParams}}{{#authMethods}}{{#isBasicBearer}}String -> {{/isBasicBearer}}{{/authMethods}}Api.Request {{^responses}}(){{/responses}}{{#responses}}{{#is2xx}}{{^dataType}}(){{/dataType}}{{#isMap}}(Dict.Dict String {{/isMap}}{{#isArray}}(List {{#items}}{{#isModel}}Api.Data.{{/isModel}}{{/items}}{{/isArray}}{{^isArray}}{{^primitiveType}}{{^isUuid}}Api.Data.{{/isUuid}}{{/primitiveType}}{{/isArray}}{{dataType}}{{#isArray}}){{/isArray}}{{#isMap}}){{/isMap}}{{/is2xx}}{{/responses}} {{operationId}}{{#allParams}} {{>paramName}}{{/allParams}}{{#authMethods}}{{#isBasicBearer}} auth_token{{/isBasicBearer}}{{/authMethods}} = Api.request "{{httpMethod}}" diff --git a/modules/openapi-generator/src/main/resources/elm/recordFieldValueDecoder.mustache b/modules/openapi-generator/src/main/resources/elm/recordFieldValueDecoder.mustache index d182a19974e..d01b75352d4 100644 --- a/modules/openapi-generator/src/main/resources/elm/recordFieldValueDecoder.mustache +++ b/modules/openapi-generator/src/main/resources/elm/recordFieldValueDecoder.mustache @@ -1 +1 @@ -{{#isArray}}(Json.Decode.list {{/isArray}}{{#isMap}}(Json.Decode.dict {{/isMap}}{{#items}}{{>recordFieldValueDecoder}}{{/items}}{{^isContainer}}{{#isCircularReference}}(Json.Decode.lazy (\_ -> {{/isCircularReference}}{{>fieldDecoder}}{{#isCircularReference}})){{/isCircularReference}}{{/isContainer}}{{#isArray}}){{/isArray}}{{#isMap}}){{/isMap}} \ No newline at end of file +{{#isArray}}(Json.Decode.list {{/isArray}}{{#isMap}}(Json.Decode.dict {{/isMap}}{{#items}}{{>recordFieldValueDecoder}}{{/items}}{{^isArray}}{{#isCircularReference}}(Json.Decode.lazy (\_ -> {{/isCircularReference}}{{>fieldDecoder}}{{#isCircularReference}})){{/isCircularReference}}{{/isArray}}{{#isArray}}){{/isArray}}{{#isMap}}){{/isMap}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/apiDelegate.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/apiDelegate.mustache index db054a92c30..d45f9f79f2e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/apiDelegate.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/apiDelegate.mustache @@ -32,7 +32,7 @@ interface {{classname}}Delegate { /** * @see {{classname}}#{{operationId}} */ - fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{{dataType}}}{{/isBodyParam}}{{/isFile}}{{#isFile}}Resource?{{/isFile}}{{^-last}}, + fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{>optionalDataType}}{{/isFile}}{{#isFile}}Resource?{{/isFile}}{{^-last}}, {{/-last}}{{/allParams}}): {{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} { {{>methodBody}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache index b44f43adf85..ec3c8fd6983 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache @@ -1,5 +1,4 @@ -{{#useBeanValidation}}{{#required}}{{^isReadOnly}} - @get:NotNull{{/isReadOnly}}{{/required}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} - @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}}{{#deprecated}} +{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}}{{#deprecated}} @Deprecated(message = ""){{/deprecated}} @field:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/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-spring/dataClassReqVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache index b67cb59905b..963baa8f9af 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache @@ -1,4 +1,3 @@ -{{#useBeanValidation}}{{#required}}{{^isReadOnly}} - @get:NotNull {{/isReadOnly}}{{/required}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} - @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}} - @field:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isReadOnly}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}}{{/isReadOnly}} \ No newline at end of file +{{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}} + @field:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{nameInCamelCase}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isReadOnly}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}}{{/isReadOnly}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/README.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/README.mustache new file mode 100644 index 00000000000..ecf0a6edb02 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/README.mustache @@ -0,0 +1,48 @@ +# {{packageName}} - Kotlin database library for {{appName}} + +## Requires + +{{#jvm}} +* Kotlin 1.3.61 +* Gradle 4.9 +{{/jvm}} +{{#multiplatform}} +* Kotlin 1.3.50 +{{/multiplatform}} + +## Build + +{{#jvm}} +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +{{/jvm}} +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Supports Mapper using API model classes. +* Supports SQLite types. + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/build.gradle.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/build.gradle.mustache new file mode 100644 index 00000000000..55621198b63 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/build.gradle.mustache @@ -0,0 +1,35 @@ +group '{{groupId}}' +version '{{artifactVersion}}' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.72' + ext.ktorm_version = '3.2.0' + + repositories { + maven { url "https://repo1.maven.org/maven2" } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' + +repositories { + maven { url "https://repo1.maven.org/maven2" } +} + +test { + useJUnitPlatform() +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.ktorm:ktorm-core:$ktorm_version" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.1.0" +} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class.mustache new file mode 100644 index 00000000000..e15a7b7a90c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class.mustache @@ -0,0 +1,102 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{^discriminator}} +/** + * {{{description}}} +{{#allVars}} + * @param {{{name}}} {{{description}}} +{{/allVars}} + */ +{{#isDeprecated}} +@Deprecated(message = "This schema is deprecated.") +{{/isDeprecated}} +{{#nonPublicApi}}internal {{/nonPublicApi}}object {{{classname}}}s : BaseTable<{{{classname}}}>("{{#tableDefinition}}{{{tblName}}}{{/tableDefinition}}") { +{{#allVars}} +{{^isArray}} +{{#isEnum}} +{{#required}}{{>data_class_enum_req}}{{/required}}{{^required}}{{>data_class_enum_opt}}{{/required}} +{{/isEnum}} +{{^isEnum}} +{{#required}}{{>data_class_field_req}}{{/required}}{{^required}}{{>data_class_field_opt}}{{/required}} +{{/isEnum}} +{{/isArray}} +{{/allVars}} + + /** + * Create an entity of type {{{classname}}} from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = {{{classname}}}( +{{#allVars}} +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{^isArray}} +{{#relation}} +{{#required}}{{>data_class_bind_ref_req}}{{/required}}{{^required}}{{>data_class_bind_ref_opt}}{{/required}}{{^-last}},{{/-last}} +{{/relation}} +{{^relation}} +{{#required}}{{>data_class_bind_field_req}}{{/required}}{{^required}}{{>data_class_bind_field_opt}}{{/required}}{{^-last}},{{/-last}} +{{/relation}} +{{/isArray}} +{{#isArray}} +{{#required}}{{>data_class_bind_list_req}}{{/required}}{{^required}}{{>data_class_bind_list_opt}}{{/required}}{{^-last}},{{/-last}} +{{/isArray}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{/allVars}} + ) + + /** + * Assign all the columns from the entity of type {{{classname}}} to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = {{{classname}}}() + * database.update({{{classname}}}s, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: {{{classname}}}) { + this.apply { +{{#allVars}} +{{^isArray}} +{{>data_class_set}} +{{/isArray}} +{{/allVars}} + } + } + +} + +{{#allVars}} +{{#isArray}} +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{#isDeprecated}} +@Deprecated(message = "This schema is deprecated.") +{{/isDeprecated}} +{{#relationDefinition}} + +{{#nonPublicApi}}internal {{/nonPublicApi}}object {{{relName}}} : BaseTable>("{{{relTblName}}}") { + val {{{pkName}}} = {{{pkColType}}}("{{{pkColName}}}") + val {{{fkName}}} = {{{fkColType}}}("{{{fkColName}}}") + + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean): Pair<{{{pkColKotlinType}}}, {{{fkColKotlinType}}}> = + Pair(row[{{{pkName}}}] ?: {{#pkIsString}}""{{/pkIsString}}{{#pkIsNumeric}}0{{/pkIsNumeric}}, row[{{{fkName}}}] ?: {{#fkIsString}}""{{/fkIsString}}{{#fkIsNumeric}}0{{/fkIsNumeric}}) + + fun AssignmentsBuilder.assignFrom(entity: Pair<{{{pkColKotlinType}}}, {{{fkColKotlinType}}}>) { + this.apply { + set({{{relName}}}.{{{pkName}}}, entity.first) + set({{{relName}}}.{{{fkName}}}, entity.second) + } + } + +} +{{/relationDefinition}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{/isArray}} +{{/allVars}} +{{/discriminator}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_opt.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_opt.mustache new file mode 100644 index 00000000000..9cb5892ecb7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_opt.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = row[{{{name}}}] {{#defaultvalue}}?: {{{defaultvalue}}}{{/defaultvalue}} /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_req.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_req.mustache new file mode 100644 index 00000000000..b3af9c69906 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_field_req.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = row[{{{name}}}]{{#isEnum}} ?: {{{classname}}}.{{{nameInCamelCase}}}.valueOf({{#isString}}""{{/isString}}{{#isNumeric}}0{{/isNumeric}}){{/isEnum}}{{^isEnum}}{{#isString}} ?: ""{{/isString}}{{#isNumeric}} ?: 0{{/isNumeric}}{{#isBoolean}} ?: false{{/isBoolean}}{{/isEnum}} /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_opt.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_opt.mustache new file mode 100644 index 00000000000..7820b16e3bf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_opt.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = emptyList() /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_req.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_req.mustache new file mode 100644 index 00000000000..bc668b27fd4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_list_req.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = emptyList() /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_opt.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_opt.mustache new file mode 100644 index 00000000000..d422a1a812c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_opt.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = {{{colKotlinType}}}s.createEntity(row, withReferences) /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_req.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_req.mustache new file mode 100644 index 00000000000..0974295d86f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_bind_ref_req.mustache @@ -0,0 +1 @@ +{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = {{{colKotlinType}}}s.createEntity(row, withReferences) /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_doc.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_doc.mustache new file mode 100644 index 00000000000..0046d259079 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_doc.mustache @@ -0,0 +1,20 @@ +# Table {{#vendorExtensions}}{{#x-ktorm-schema}}{{#tableDefinition}}`{{tblName}}`{{/tableDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}} +(mapped from: {{classname}}) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +{{#allVars}}**{{name}}** | {{^isArray}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}}{{colName}} | {{colType}}{{#colTypeArgs}}{{#-first}}({{/-first}}{{#isString}}'{{/isString}}{{argVal}}{{#isString}}'{{/isString}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/colTypeArgs}}{{#colUnsigned}} UNSIGNED{{/colUnsigned}}{{#colNotNull}} NOT NULL{{/colNotNull}}{{#colPrimaryKey}} PRIMARY KEY{{#isNumeric}} AUTOINCREMENT{{/isNumeric}}{{/colPrimaryKey}} | {{#colDefault}}{{#isString}}'{{defaultValue}}'{{/isString}}{{^isString}}{{defaultValue}}{{/isString}}{{/colDefault}}{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{/isArray}}{{#isArray}}`One-To-Many` | `----` | `----` {{/isArray}} | {{#isEnum}}[**{{baseName}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{^isArray}}{{#relation}} [foreignkey]{{/relation}}{{/isArray}}{{/x-ktorm-schema}}{{/vendorExtensions}} +{{/allVars}} +{{#allVars}}{{#isArray}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#relationDefinition}} + +# **Table `{{{relTblName}}}`** +(mapped from: {{relName}}) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +{{{pkName}}} | {{{pkColName}}} | {{{pkColType}}} | | {{{pkColKotlinType}}} | Primary Key | *one* +{{{fkName}}} | {{{fkColName}}} | {{{fkColType}}} | | {{{fkColKotlinType}}} | Foreign Key | *many* +{{/relationDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{/isArray}} +{{/allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_opt.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_opt.mustache new file mode 100644 index 00000000000..03d7f8d40db --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_opt.mustache @@ -0,0 +1,2 @@ +{{#deprecated}} @Deprecated(message = "This property is deprecated.") +{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}").transform({ {{{classname}}}.{{{nameInCamelCase}}}.valueOf(it ?: {{#allowableValues}}{{#enumVars}}{{#-first}}{{{value}}}{{/-first}}{{/enumVars}}{{/allowableValues}}) }, { it.value }) /* null */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_req.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_req.mustache new file mode 100644 index 00000000000..33a3004fbc7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_enum_req.mustache @@ -0,0 +1,2 @@ +{{#deprecated}} @Deprecated(message = "This property is deprecated.") +{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}").transform({ {{{classname}}}.{{{nameInCamelCase}}}.valueOf(it) }, { it.value }){{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_opt.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_opt.mustache new file mode 100644 index 00000000000..134330d4539 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_opt.mustache @@ -0,0 +1,2 @@ +{{#deprecated}} @Deprecated(message = "This property is deprecated.") +{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}") /* null */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_req.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_req.mustache new file mode 100644 index 00000000000..09a42c1a1e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_field_req.mustache @@ -0,0 +1,2 @@ +{{#deprecated}} @Deprecated(message = "This property is deprecated.") +{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}"){{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_set.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_set.mustache new file mode 100644 index 00000000000..39ce7c54fae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/data_class_set.mustache @@ -0,0 +1 @@ + set({{{classname}}}s.{{{name}}}, entity.{{{name}}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/enum_class.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/enum_class.mustache new file mode 100644 index 00000000000..f1a8b67eeff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/enum_class.mustache @@ -0,0 +1,61 @@ +{{^multiplatform}} +{{#gson}} +import com.google.gson.annotations.SerializedName +{{/gson}} +{{#moshi}} +import com.squareup.moshi.Json +{{/moshi}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonProperty +{{/jackson}} +{{/multiplatform}} +{{#multiplatform}} +import kotlinx.serialization.* +import kotlinx.serialization.internal.CommonEnumSerializer +{{/multiplatform}} + +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}} +{{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}){ + +{{#allowableValues}}{{#enumVars}} + {{^multiplatform}} + {{#moshi}} + @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) + {{/moshi}} + {{#gson}} + @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) + {{/gson}} + {{#jackson}} + @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) + {{/jackson}} + {{/multiplatform}} + {{#isArray}} + {{#isList}} + {{&name}}(listOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/isList}} + {{^isList}} + {{&name}}(arrayOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/isList}} + {{/isArray}} + {{^isArray}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/isArray}} + +{{/enumVars}}{{/allowableValues}} + + /** + This override toString avoids using the enum var name and uses the actual api value instead. + In cases the var name and value are different, the client would send incorrect enums to the server. + **/ + override fun toString(): String { + return value{{^isString}}.toString(){{/isString}} + } + +{{#multiplatform}} + {{#nonPublicApi}}internal {{/nonPublicApi}}object Serializer : CommonEnumSerializer<{{classname}}>("{{classname}}", values(), values().map { it.value.toString() }.toTypedArray()) +{{/multiplatform}} +} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/enum_doc.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/enum_doc.mustache new file mode 100644 index 00000000000..fcb3d7e61aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/enum_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} + * `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/ktorm_schema.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/ktorm_schema.mustache new file mode 100644 index 00000000000..56c627d2d60 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/ktorm_schema.mustache @@ -0,0 +1,179 @@ +{{#defaultDatabaseName}} +-- +-- Database: `{{{defaultDatabaseName}}}` +-- +CREATE DATABASE IF NOT EXISTS `{{{defaultDatabaseName}}}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +{{/defaultDatabaseName}} + +{{#models}}{{#model}}{{#hasVars}}{{^isArrayModel}} +-- -------------------------------------------------------------------------- +-- Table structure{{#vendorExtensions}}{{#x-ktorm-schema}}{{#tableDefinition}} for table `{{tblName}}`{{/tableDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}} generated from model '{{classVarName}}' +{{#description}} +-- {{description}} +{{/description}} +-- + +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{#tableDefinition}} +CREATE TABLE IF NOT EXISTS {{#defaultDatabaseName}}`{{{defaultDatabaseName}}}`.{{/defaultDatabaseName}}`{{tblName}}` ( +{{/tableDefinition}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{#allVars}} +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{#columnDefinition}} +{{^isArray}} + `{{colName}}` {{colType}}{{#colTypeArgs}}{{#-first}}({{/-first}}{{#isString}}'{{/isString}}{{argVal}}{{#isString}}'{{/isString}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/colTypeArgs}}{{#colUnsigned}} UNSIGNED{{/colUnsigned}}{{#colNotNull}} NOT NULL{{/colNotNull}}{{#colPrimaryKey}} PRIMARY KEY{{#isNumeric}} AUTOINCREMENT{{/isNumeric}}{{/colPrimaryKey}}{{#colDefault}} DEFAULT {{#isString}}'{{defaultValue}}'{{/isString}}{{^isString}}{{defaultValue}}{{/isString}}{{/colDefault}}{{#colComment}} /*{{colComment}}*/{{/colComment}}{{^-last}},{{/-last}} +{{/isArray}} +{{/columnDefinition}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{/allVars}} +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{#tableDefinition}} +); {{#tblComment}} /*{{tblComment}}*/{{/tblComment}} + +{{/tableDefinition}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{#allVars}} +{{#isArray}} +{{#vendorExtensions}} +{{#x-ktorm-schema}} +{{#relationDefinition}} +-- -------------------------------------------------------------------------- +-- Table structure for table `{{relTblName}}` generated from model '{{relName}}' +{{#colComment}} +-- {{colComment}} +{{/colComment}} + +CREATE TABLE IF NOT EXISTS {{#defaultDatabaseName}}`{{{defaultDatabaseName}}}`.{{/defaultDatabaseName}}`{{relTblName}}` ( + `{{{pkColName}}}` {{{pkColType}}} NOT NULL + `{{{fkColName}}}` {{{fkColType}}} NOT NULL +); + +{{/relationDefinition}} +{{/x-ktorm-schema}} +{{/vendorExtensions}} +{{/isArray}} +{{/allVars}} +{{/isArrayModel}}{{/hasVars}}{{/model}}{{/models}} +{{#hasOAuthMethods}} +-- +-- OAuth2 framework tables +-- Thanks to https://github.com/dsquier/oauth2-server-php-mysql repo +-- + +-- +-- Table structure for table `oauth_clients` +-- +CREATE TABLE IF NOT EXISTS `oauth_clients` ( + `client_id` VARCHAR(80) NOT NULL, + `client_secret` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) DEFAULT NULL, + `grant_types` VARCHAR(80) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + PRIMARY KEY (`client_id`) +); + +-- +-- Table structure for table `oauth_access_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_access_tokens` ( + `access_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`access_token`) +); + +-- +-- Table structure for table `oauth_authorization_codes` +-- +CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` ( + `authorization_code` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) NOT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `id_token` VARCHAR(1000) DEFAULT NULL, + PRIMARY KEY (`authorization_code`) +); + +-- +-- Table structure for table `oauth_refresh_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` ( + `refresh_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`refresh_token`) +); + +-- +-- Table structure for table `oauth_users` +-- +CREATE TABLE IF NOT EXISTS `oauth_users` ( + `username` VARCHAR(80) DEFAULT NULL, + `password` VARCHAR(255) DEFAULT NULL, + `first_name` VARCHAR(80) DEFAULT NULL, + `last_name` VARCHAR(80) DEFAULT NULL, + `email` VARCHAR(2000) DEFAULT NULL, + `email_verified` TINYINT(1) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL +); + +-- +-- Table structure for table `oauth_scopes` +-- +CREATE TABLE IF NOT EXISTS `oauth_scopes` ( + `scope` VARCHAR(80) NOT NULL, + `is_default` TINYINT(1) DEFAULT NULL, + PRIMARY KEY (`scope`) +); + +-- +-- Table structure for table `oauth_jwt` +-- +CREATE TABLE IF NOT EXISTS `oauth_jwt` ( + `client_id` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) NOT NULL +); + +-- +-- Table structure for table `oauth_jti` +-- +CREATE TABLE IF NOT EXISTS `oauth_jti` ( + `issuer` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `audiance` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `jti` VARCHAR(2000) NOT NULL +); + +-- +-- Table structure for table `oauth_public_keys` +-- +CREATE TABLE IF NOT EXISTS `oauth_public_keys` ( + `client_id` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) DEFAULT NULL, + `private_key` VARCHAR(2000) DEFAULT NULL, + `encryption_algorithm` VARCHAR(100) DEFAULT 'RS256' +); +{{/hasOAuthMethods}} + +-- +-- Table structure for table `_db_version` +-- +CREATE TABLE IF NOT EXISTS `_db_version` ( + `version` LONG DEFAULT 1 +); diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/licenseInfo.mustache new file mode 100644 index 00000000000..3a547de74bb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/model.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/model.mustache new file mode 100644 index 00000000000..20216d0dbd8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/model.mustache @@ -0,0 +1,13 @@ +{{>licenseInfo}} +package {{modelPackage}} + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import {{{importModelPackageName}}}.* + +{{#models}} +{{#model}} +{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{#isAlias}}typealias {{classname}} = {{{dataType}}}{{/isAlias}}{{^isAlias}}{{>data_class}}{{/isAlias}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/model_doc.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/model_doc.mustache new file mode 100644 index 00000000000..198ea33c57c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/model_doc.mustache @@ -0,0 +1,3 @@ +{{#models}}{{#model}} +{{#isEnum}}{{>enum_doc}}{{/isEnum}}{{^isEnum}}{{>data_class_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/ktorm-schema/settings.gradle.mustache b/modules/openapi-generator/src/main/resources/ktorm-schema/settings.gradle.mustache new file mode 100644 index 00000000000..0fab92c481a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ktorm-schema/settings.gradle.mustache @@ -0,0 +1,2 @@ +{{#multiplatform}}enableFeaturePreview('GRADLE_METADATA') +{{/multiplatform}}rootProject.name = '{{artifactId}}' \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache b/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache index ef1f3e350df..1ac78f767bd 100644 --- a/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache @@ -73,7 +73,7 @@ function Initialize-{{{apiNamePrefix}}}{{{classname}}} { {{#vars}} {{^isNullable}} {{#required}} - if (!${{{name}}}) { + if (${{{name}}} -eq $null) { throw "invalid value for '{{{name}}}', '{{{name}}}' cannot be null." } @@ -246,12 +246,12 @@ function ConvertFrom-{{{apiNamePrefix}}}JsonTo{{{classname}}} { {{#requiredVars}} {{#-first}} If ([string]::IsNullOrEmpty($Json) -or $Json -eq "{}") { # empty json - throw "Error! Empty JSON cannot be serialized due to the required property `{{{baseName}}}` missing." + throw "Error! Empty JSON cannot be serialized due to the required property '{{{baseName}}}' missing." } {{/-first}} if (!([bool]($JsonParameters.PSobject.Properties.name -match "{{{baseName}}}"))) { - throw "Error! JSON cannot be serialized due to the required property `{{{baseName}}}` missing." + throw "Error! JSON cannot be serialized due to the required property '{{{baseName}}}' missing." } else { ${{name}} = $JsonParameters.PSobject.Properties["{{{baseName}}}"].value } diff --git a/modules/openapi-generator/src/main/resources/ruby-client/README.mustache b/modules/openapi-generator/src/main/resources/ruby-client/README.mustache index dafacf98ad5..e35995e6339 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/README.mustache @@ -72,9 +72,9 @@ require '{{{gemName}}}' # Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}} config.access_token = 'YOUR_BEARER_TOKEN'{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} - config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' + config.api_key['{{{name}}}'] = 'YOUR API KEY' # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) - #config.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} + # config.api_key_prefix['{{{name}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} {{/authMethods}}end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache index 6723bb756c6..2741a73794e 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache @@ -182,7 +182,7 @@ module {{moduleName}} case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] - else fail ArgumentError, 'Authentication token must be in `query` of `header`' + else fail ArgumentError, 'Authentication token must be in `query` or `header`' end end end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_doc.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_doc.mustache index bdeeb568912..81fc865534d 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_doc.mustache @@ -37,9 +37,9 @@ require '{{{gemName}}}' # Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}} config.access_token = 'YOUR_BEARER_TOKEN'{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} - config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' + config.api_key['{{{name}}}'] = 'YOUR API KEY' # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) - # config.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} + # config.api_key_prefix['{{{name}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} {{/authMethods}}end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache b/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache index fd1ad422ddb..26d324489b9 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache @@ -169,11 +169,13 @@ module {{moduleName}} # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth - def api_key_with_prefix(param_name) + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + "#{@api_key_prefix[param_name]} #{key}" else - @api_key[param_name] + key end end @@ -192,7 +194,7 @@ module {{moduleName}} type: 'api_key', in: {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, key: '{{keyParamName}}', - value: api_key_with_prefix('{{keyParamName}}') + value: api_key_with_prefix('{{name}}'{{#vendorExtensions.x-auth-id-alias}}, '{{.}}'{{/vendorExtensions.x-auth-id-alias}}) }, {{/isApiKey}} {{#isBasic}} diff --git a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache index 68d624fb64f..2630944598b 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache @@ -7,7 +7,7 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct APIHelper { - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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 @@ import Foundation return destination } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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: ",") + if let collection = item.value as? [Any?] { + result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -46,16 +46,16 @@ import Foundation } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + if let collection = source as? [Any?] { + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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 { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + if let collection = item.value as? [Any?] { + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { @@ -69,4 +69,3 @@ import Foundation return destination } } - diff --git a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache index 5429af6973f..d672115546f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache @@ -9,7 +9,7 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var basePath = "{{{basePath}}}" {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential? - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String:String] = [:]{{#useAlamofire}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String: String] = [:]{{#useAlamofire}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory(){{/useAlamofire}}{{#useURLSession}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory(){{/useURLSession}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiResponseQueue: DispatchQueue = .main @@ -17,28 +17,26 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let parameters: [String:Any]? - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let isBody: Bool + var headers: [String: String] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let parameters: [String: Any]? {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let method: String {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let URLString: String /// Optional block to obtain a reference to the request's progress instance when available.{{#useURLSession}} /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client.{{/useURLSession}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> ())? + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> Void)? - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders({{projectName}}API.customHeaders) } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders:[String:String]) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -61,5 +59,5 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache index 9c30d7413b9..3f6269c23ab 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache @@ -1,3 +1,3 @@ {{#useAlamofire}}github "Alamofire/Alamofire" ~> 4.9.1{{/useAlamofire}}{{#usePromiseKit}} -github "mxcl/PromiseKit" ~> 6.12.0{{/usePromiseKit}}{{#useRxSwift}} -github "ReactiveX/RxSwift" ~> 5.0.1{{/useRxSwift}} +github "mxcl/PromiseKit" ~> 6.13.1{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 5.1.1{{/useRxSwift}} diff --git a/modules/openapi-generator/src/main/resources/swift5/CodableHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/CodableHelper.mustache index baad56cca2f..d5b1c1e0a29 100644 --- a/modules/openapi-generator/src/main/resources/swift5/CodableHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/CodableHelper.mustache @@ -45,4 +45,4 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encode(_ value: T) -> Swift.Result where T: Encodable { return Swift.Result { try self.jsonEncoder.encode(value) } } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache index b6e8d28fe4b..47c874815b9 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache @@ -7,10 +7,10 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index 311b4bf3b31..1a23697a04b 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -109,24 +109,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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 { - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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 } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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 } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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) { @@ -177,10 +177,10 @@ extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { return Array(200 ..< 300).contains(statusCode) } -} +}{{#usePromiseKit}} -{{#usePromiseKit}}extension RequestBuilder { - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func execute() -> Promise> { +extension RequestBuilder { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func execute() -> Promise> { let deferred = Promise>.pending() self.execute { result in switch result { diff --git a/modules/openapi-generator/src/main/resources/swift5/JSONDataEncoding.mustache b/modules/openapi-generator/src/main/resources/swift5/JSONDataEncoding.mustache index 71cdb1da93c..e227058129b 100644 --- a/modules/openapi-generator/src/main/resources/swift5/JSONDataEncoding.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/JSONDataEncoding.mustache @@ -41,7 +41,7 @@ import Foundation } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func encodingParameters(jsonData: Data?) -> [String: Any]? { - var returnedParams: [String: Any]? = nil + var returnedParams: [String: Any]? if let jsonData = jsonData, !jsonData.isEmpty { var params: [String: Any] = [:] params[jsonDataKey] = jsonData diff --git a/modules/openapi-generator/src/main/resources/swift5/JSONEncodingHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/JSONEncodingHelper.mustache index 0191a8fd84a..0eae73e1b39 100644 --- a/modules/openapi-generator/src/main/resources/swift5/JSONEncodingHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/JSONEncodingHelper.mustache @@ -9,8 +9,8 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class JSONEncodingHelper { - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { - var params: [String: Any]? = nil + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? // Encode the Encodable object if let encodableObj = encodableObj { @@ -27,7 +27,7 @@ import Foundation } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { - var params: [String: Any]? = nil + var params: [String: Any]? if let encodableObj = encodableObj { do { @@ -41,5 +41,5 @@ import Foundation return params } - + } diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index 9a3f50d5d8e..74ce973b287 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -10,11 +10,11 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse : Error { - case error(Int, Data?, Error) +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) } -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DownloadException : Error { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -30,7 +30,6 @@ protocol JSONEncodable { case generalError(Error) } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Response { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let statusCode: Int {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let header: [String: String] @@ -44,7 +43,7 @@ protocol JSONEncodable { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for (key, value) in rawHeader { if let key = key.base as? String, let value = value as? String { header[key] = value diff --git a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache index e25eab49911..c0539662ce7 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache @@ -27,10 +27,10 @@ Pod::Spec.new do |s| {{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/**/*.swift' {{#usePromiseKit}} - s.dependency 'PromiseKit/CorePromise', '~> 6.12.0' + s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' {{/usePromiseKit}} {{#useRxSwift}} - s.dependency 'RxSwift', '~> 5.0.0' + s.dependency 'RxSwift', '~> 5.1.1' {{/useRxSwift}} {{#useAlamofire}} s.dependency 'Alamofire', '~> 4.9.1' diff --git a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache index 3b57c69e104..a81137ae138 100644 --- a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache @@ -3,7 +3,7 @@ targets: {{projectName}}: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [{{projectName}}] info: path: ./Info.plist diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index b5aedeb389b..18d3e6b3045 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -8,9 +8,8 @@ import Foundation{{#usePromiseKit}} import PromiseKit{{/usePromiseKit}}{{#useRxSwift}} import RxSwift{{/useRxSwift}}{{#useCombine}} -import Combine{{/useCombine}} +import Combine{{/useCombine}}{{#swiftUseApiNamespace}} -{{#swiftUseApiNamespace}} extension {{projectName}}API { {{/swiftUseApiNamespace}} @@ -48,7 +47,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?,_ error: Error?) -> Void)) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { {{#returnType}} @@ -232,9 +231,9 @@ extension {{projectName}}API { {{/bodyParam}} {{^bodyParam}} {{#hasFormParams}} - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ {{#formParams}} - {{> _param}}{{^-last}},{{/-last}} + {{> _param}}, {{/formParams}} ] @@ -242,24 +241,28 @@ extension {{projectName}}API { let parameters = APIHelper.convertBoolToString(nonNullParameters) {{/hasFormParams}} {{^hasFormParams}} - let parameters: [String:Any]? = nil + let parameters: [String: Any]? = nil {{/hasFormParams}} - {{/bodyParam}}{{#hasQueryParams}} +{{/bodyParam}}{{#hasQueryParams}} var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}} {{#queryParams}} - {{> _param}}{{^-last}}, {{/-last}} + {{> _param}}, {{/queryParams}} ]){{/hasQueryParams}}{{^hasQueryParams}} - let url = URLComponents(string: URLString){{/hasQueryParams}}{{#headerParams}}{{#-first}} - let nillableHeaders: [String: Any?] = [{{/-first}} - {{> _param}}{{^-last}},{{/-last}}{{#-last}} + let url = URLComponents(string: URLString){{/hasQueryParams}} + + let nillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}} + :{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}} + "Content-Type": {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasFormParams}}{{#headerParams}} + {{> _param}},{{/headerParams}} ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders){{/-last}}{{/headerParams}} + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} - return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, isBody: {{hasBodyParam}}{{#headerParams}}{{#-first}}, headers: headerParameters{{/-first}}{{/headerParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache index 9b5389031e9..ef593fe7597 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -21,8 +21,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore = SynchronizedDictionary() {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireRequestBuilder: RequestBuilder { - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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) + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -39,7 +39,20 @@ private var managerStore = SynchronizedDictionary URLRequest? { - let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + encoding = JSONDataEncoding() + } + guard let originalRequest = try? URLRequest(url: URLString, method: HTTPMethod(rawValue: method)!, headers: buildHeaders()) else { return nil } return try? encoding.encode(originalRequest, with: parameters) } @@ -59,62 +72,78 @@ private var managerStore = SynchronizedDictionary DataRequest { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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 {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let managerId:String = UUID().uuidString + let managerId = 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() + guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } - let xMethod = Alamofire.HTTPMethod(rawValue: method) - let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } - .map { $0.0 } + let encoding: ParameterEncoding? - if fileKeys.count > 0 { - manager.upload(multipartFormData: { mpForm in - for (k, v) in self.parameters! { - switch v { - case let fileURL as URL: - if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { - mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = nil + + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } else { + mpForm.append(fileURL, withName: k) + } + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + default: + fatalError("Unprocessable value \(v) with key \(k)") } - else { - mpForm.append(fileURL, withName: k) + } + }, to: URLString, method: xMethod, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, apiResponseQueue, completion) + case .failure(let encodingError): + apiResponseQueue.async { + completion(.failure(ErrorResponse.error(415, nil, nil, encodingError))) } - case let string as String: - mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) - case let number as NSNumber: - mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) - default: - fatalError("Unprocessable value \(v) with key \(k)") } - } - }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in - switch encodingResult { - case .success(let upload, _, _): - if let onProgressReady = self.onProgressReady { - onProgressReady(upload.uploadProgress) - } - self.processRequest(request: upload, managerId, apiResponseQueue, completion) - case .failure(let encodingError): - apiResponseQueue.async{ - completion(.failure(ErrorResponse.error(415, nil, encodingError))) - } - } - }) - } else { - let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + }) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = URLEncoding(destination: .httpBody) + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + + if let encoding = encoding { + let request = makeRequest(manager: manager, method: xMethod, encoding: encoding, headers: headers) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } processRequest(request: request, managerId, apiResponseQueue, completion) } - } fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { @@ -132,14 +161,14 @@ private var managerStore = SynchronizedDictionary String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -228,7 +257,7 @@ private var managerStore = SynchronizedDictionary String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -262,7 +291,7 @@ private var managerStore = SynchronizedDictionary URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -273,7 +302,7 @@ private var managerStore = SynchronizedDictionary: AlamofireRequestBuilder { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let credential = self.credential { @@ -290,36 +319,36 @@ private var managerStore = SynchronizedDictionary URLRequest { let urlRequest = try urlRequest.asURLRequest() - + return self.encode(urlRequest, with: parameters) } } diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache index 0f19cdfbcf9..594e9c7c1cd 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache @@ -14,7 +14,7 @@ class URLSessionRequestBuilderFactory: RequestBuilderFactory { return URLSessionRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return URLSessionDecodableRequestBuilder.self } } @@ -23,16 +23,10 @@ class URLSessionRequestBuilderFactory: RequestBuilderFactory { private var urlSessionStore = SynchronizedDictionary() {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionRequestBuilder: RequestBuilder { - - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - + // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() - + /** May be assigned if you want to control the authentication challenges. */ @@ -44,12 +38,13 @@ private var urlSessionStore = SynchronizedDictionary() - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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) + + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } - + /** May be overridden by a subclass if you want to control the URLSession configuration. @@ -77,71 +72,76 @@ private var urlSessionStore = SynchronizedDictionary() May be overridden by a subclass if you want to control the URLRequest configuration (e.g. to override the cache policy). */ - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) throws -> URLRequest { - + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + guard let url = URL(string: URLString) else { throw DownloadException.requestMissingURL } - + var originalRequest = URLRequest(url: url) - + originalRequest.httpMethod = method.rawValue - + headers.forEach { key, value in originalRequest.setValue(value, forHTTPHeaderField: key) } - + buildHeaders().forEach { key, value in originalRequest.setValue(value, forHTTPHeaderField: key) } - + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) - + return modifiedRequest } override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId:String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - + guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } - + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } - + do { let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) - + let dataTask = urlSession.dataTask(with: request) { [weak self] data, response, error in - + guard let self = self else { return } - + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { - + taskCompletionShouldRetry(data, response, error) { [weak self] shouldRetry in - + guard let self = self else { return } - + if shouldRetry { cleanupRequest() self.execute(apiResponseQueue, completion) @@ -157,94 +157,93 @@ private var urlSessionStore = SynchronizedDictionary() } } } - + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { onProgressReady?(dataTask.progress) } - + dataTask.resume() - + } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } - + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } switch T.self { case is String.Type: - + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - + completion(.success(Response(response: httpResponse, body: body as? T))) - + case is URL.Type: do { - + guard error == nil else { throw DownloadException.responseFailed } - + guard let data = data else { throw DownloadException.responseDataMissing } - + let fileManager = FileManager.default let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] let requestURL = try self.getURL(from: urlRequest) - + var requestPath = try self.getPath(from: requestURL) - + if let headerFileName = self.getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") } - + let filePath = documentsDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path - + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - + completion(.success(Response(response: httpResponse, body: filePath as? T))) - + } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } - + case is Void.Type: - + completion(.success(Response(response: httpResponse, body: nil))) - + default: - + completion(.success(Response(response: httpResponse, body: data as? T))) } } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func buildHeaders() -> [String: String] { - var httpHeaders: [String : String] = [:] + var httpHeaders: [String: String] = [:] for (key, value) in self.headers { httpHeaders[key] = value } @@ -254,7 +253,7 @@ private var urlSessionStore = SynchronizedDictionary() return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -273,7 +272,7 @@ private var urlSessionStore = SynchronizedDictionary() filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -282,7 +281,7 @@ private var urlSessionStore = SynchronizedDictionary() } - 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 @@ -296,7 +295,7 @@ private var urlSessionStore = SynchronizedDictionary() } - 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 @@ -307,62 +306,62 @@ private var urlSessionStore = SynchronizedDictionary() } -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } switch T.self { case is String.Type: - + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - + completion(.success(Response(response: httpResponse, body: body as? T))) - + case is Void.Type: - + completion(.success(Response(response: httpResponse, body: nil))) - + case is Data.Type: - + completion(.success(Response(response: httpResponse, body: data as? T))) - + default: - + guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } - + let decodeResult = CodableHelper.decode(T.self, from: data) - + switch decodeResult { case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } } -fileprivate class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate { - +private class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate { + var credential: URLCredential? - + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { @@ -405,13 +404,13 @@ fileprivate class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataD func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest } -fileprivate class URLEncoding: ParameterEncoding { - func encode(_ urlRequest: URLRequest, with parameters: [String : Any]?) throws -> URLRequest { - +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + var urlRequest = urlRequest - + guard let parameters = parameters else { return urlRequest } - + guard let url = urlRequest.url else { throw DownloadException.requestMissingURL } @@ -420,12 +419,12 @@ fileprivate class URLEncoding: ParameterEncoding { urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) urlRequest.url = urlComponents.url } - + return urlRequest } } -fileprivate class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -436,13 +435,13 @@ fileprivate class FileUploadEncoding: ParameterEncoding { func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { var urlRequest = urlRequest - + guard let parameters = parameters, !parameters.isEmpty else { return urlRequest } - + let boundary = "Boundary-\(UUID().uuidString)" - + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { @@ -482,7 +481,7 @@ fileprivate class FileUploadEncoding: ParameterEncoding { fatalError("Unprocessable value \(value) with key \(key)") } } - + var body = urlRequest.httpBody.orEmpty body.append("\r\n--\(boundary)--\r\n") @@ -497,7 +496,7 @@ fileprivate class FileUploadEncoding: ParameterEncoding { var urlRequest = urlRequest var body = urlRequest.httpBody.orEmpty - + let fileData = try Data(contentsOf: fileURL) let mimetype = self.contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) @@ -505,7 +504,7 @@ fileprivate class FileUploadEncoding: ParameterEncoding { let fileName = fileURL.lastPathComponent // If we already added something then we need an additional newline. - if (body.count > 0) { + if body.count > 0 { body.append("\r\n") } @@ -521,20 +520,20 @@ fileprivate class FileUploadEncoding: ParameterEncoding { // The value data. body.append(fileData) - + urlRequest.httpBody = body return urlRequest } - + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { var urlRequest = urlRequest - + var body = urlRequest.httpBody.orEmpty // If we already added something then we need an additional newline. - if (body.count > 0) { + if body.count > 0 { body.append("\r\n") } @@ -569,7 +568,25 @@ fileprivate class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/modules/openapi-generator/src/main/resources/swift5/model.mustache b/modules/openapi-generator/src/main/resources/swift5/model.mustache index 15befbc24b8..a5870644a60 100644 --- a/modules/openapi-generator/src/main/resources/swift5/model.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/model.mustache @@ -6,22 +6,10 @@ // import Foundation - {{#description}} -/** {{description}} */{{/description}} -{{#isDeprecated}} -@available(*, deprecated, message: "This schema is deprecated.") -{{/isDeprecated}} -{{#isArray}} -{{> modelArray}} -{{/isArray}} -{{^isArray}} -{{#isEnum}} -{{> modelEnum}} -{{/isEnum}} -{{^isEnum}} -{{> modelObject}} -{{/isEnum}} -{{/isArray}} -{{/model}} -{{/models}} + +/** {{description}} */{{/description}}{{#isDeprecated}} +@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#isArray}} +{{> modelArray}}{{/isArray}}{{^isArray}}{{#isEnum}} +{{> modelEnum}}{{/isEnum}}{{^isEnum}} +{{> modelObject}}{{/isEnum}}{{/isArray}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache index beb0f0be344..36d1eb6e78b 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache @@ -1,8 +1,5 @@ -{{^objcCompatible}} -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { -{{/objcCompatible}} -{{#objcCompatible}} -@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { +{{/objcCompatible}}{{#objcCompatible}}@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { {{/objcCompatible}} {{#allVars}} @@ -13,14 +10,12 @@ {{#allVars}} {{#isEnum}} {{#description}}/** {{description}} */ - {{/description}}{{#deprecated}} - @available(*, deprecated, message: "This property is deprecated.") + {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{/isEnum}} {{^isEnum}} {{#description}}/** {{description}} */ - {{/description}}{{#deprecated}} - @available(*, deprecated, message: "This property is deprecated.") + {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{name}}: {{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{#objcCompatible}} {{#vendorExtensions.x-swift-optional-scalar}} @@ -33,8 +28,8 @@ {{/objcCompatible}} {{/isEnum}} {{/allVars}} - {{#hasVars}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{^required}} = nil{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) { {{#allVars}} self.{{name}} = {{name}} @@ -42,7 +37,7 @@ } {{/hasVars}} {{#additionalPropertiesType}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String:{{{additionalPropertiesType}}}] = [:] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String: {{{additionalPropertiesType}}}] = [:] {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? { get { @@ -83,11 +78,12 @@ {{/allVars}} additionalProperties = try container.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) } - {{/additionalPropertiesType}} {{^additionalPropertiesType}}{{#vendorExtensions.x-codegen-has-escaped-property-names}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: String, CodingKey, CaseIterable { {{#allVars}} - case {{name}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}}{{/allVars}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: String, CodingKey, CaseIterable { + {{#allVars}} + case {{name}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}} + {{/allVars}} } {{/vendorExtensions.x-codegen-has-escaped-property-names}}{{/additionalPropertiesType}} -} +} \ No newline at end of file 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 05c32156fe6..428af5e48b8 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 @@ -12,9 +12,9 @@ import { {{classname}} } from './{{importPath}}'; imports: [], declarations: [], exports: [], - providers: [{{^providedInRoot}} + providers: [{{#isProvidedInNone}} {{#apiInfo}}{{#apis}}{{classname}}{{^-last}}, - {{/-last}}{{/apis}}{{/apiInfo}} {{/providedInRoot}}] + {{/-last}}{{/apis}}{{/apiInfo}} {{/isProvidedInNone}}] }) export class {{apiModuleClassName}} { public static forRoot(configurationFactory: () => {{configurationClassName}}): ModuleWithProviders{{#enforceGenericModuleWithProviders}}<{{apiModuleClassName}}>{{/enforceGenericModuleWithProviders}} { 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 8adae895867..718a8b88549 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 @@ -43,14 +43,14 @@ export interface {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterIn * {{&description}} */ {{/description}} -{{^providedInRoot}} +{{#isProvidedInNone}} @Injectable() -{{/providedInRoot}} -{{#providedInRoot}} +{{/isProvidedInNone}} +{{^isProvidedInNone}} @Injectable({ - providedIn: 'root' + providedIn: '{{providedIn}}' }) -{{/providedInRoot}} +{{/isProvidedInNone}} {{#withInterfaces}} export class {{classname}} implements {{classname}}Interface { {{/withInterfaces}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache index 767a3488080..04001417a82 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache @@ -172,7 +172,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/modules/openapi-generator/src/main/resources/typescript/index.mustache b/modules/openapi-generator/src/main/resources/typescript/index.mustache index 3e4d0907d0e..b19f7f9348a 100644 --- a/modules/openapi-generator/src/main/resources/typescript/index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/index.mustache @@ -1,7 +1,8 @@ export * from "./http/http{{extensionForDeno}}"; export * from "./auth/auth{{extensionForDeno}}"; export * from "./models/all{{extensionForDeno}}"; -export { createConfiguration, Configuration } from "./configuration{{extensionForDeno}}" +export { createConfiguration } from "./configuration{{extensionForDeno}}" +export{{#platforms}}{{#deno}} type{{/deno}}{{/platforms}} { Configuration } from "./configuration{{extensionForDeno}}" export * from "./apis/exception{{extensionForDeno}}"; export * from "./servers{{extensionForDeno}}"; @@ -9,7 +10,7 @@ export * from "./servers{{extensionForDeno}}"; export { Middleware } from './middleware{{extensionForDeno}}'; {{/useRxJS}} {{^useRxJS}} -export { PromiseMiddleware as Middleware } from './middleware{{extensionForDeno}}'; +export{{#platforms}}{{#deno}} type{{/deno}}{{/platforms}} { PromiseMiddleware as Middleware } from './middleware{{extensionForDeno}}'; {{/useRxJS}} {{#useObjectParameters}} export { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{classname}}{{operationIdCamelCase}}Request, {{/operation}}Object{{classname}} as {{classname}}{{^-last}}, {{/-last}} {{/operations}}{{/apis}}{{/apiInfo}}} from './types/ObjectParamAPI{{extensionForDeno}}'; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java new file mode 100644 index 00000000000..1711eee45bd --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java @@ -0,0 +1,198 @@ +/* + * 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 + * + * https://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.confluencewiki; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.media.*; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.ConfluenceWikiCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class ConfluenceWikiTest { + + @Test(description = "convert a model with an enum") + public void converterTest() { + final StringSchema enumSchema = new StringSchema(); + enumSchema.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + final Schema model = new Schema().type("object").addProperties("name", enumSchema); + + final ConfluenceWikiCodegen codegen = new ConfluenceWikiCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.dataType, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, "null"); + Assert.assertEquals(enumVar.baseType, "string"); + Assert.assertTrue(enumVar.isEnum); + } + + @Test(description = "convert a model with an enum inside a list") + public void converterInArrayTest() { + final ArraySchema enumSchema = new ArraySchema().items( + new StringSchema().addEnumItem("Aaaa").addEnumItem("Bbbb")); + final Schema model = new Schema().type("object").addProperties("name", enumSchema); + + final DefaultCodegen codegen = new ConfluenceWikiCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.dataType, "array[String]"); + Assert.assertEquals(enumVar.datatypeWithEnum, "array[String]"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, "null"); + Assert.assertEquals(enumVar.baseType, "array"); + Assert.assertTrue(enumVar.isEnum); + + Assert.assertEquals(enumVar.mostInnerItems.baseName, "name"); + Assert.assertEquals(enumVar.mostInnerItems.dataType, "String"); + Assert.assertEquals(enumVar.mostInnerItems.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.mostInnerItems.name, "name"); + Assert.assertEquals(enumVar.mostInnerItems.defaultValue, "null"); + Assert.assertEquals(enumVar.mostInnerItems.baseType, "string"); + + Assert.assertEquals(enumVar.mostInnerItems.baseType, enumVar.items.baseType); + } + + @Test(description = "convert a model with an enum inside a list") + public void converterInArrayInArrayTest() { + final ArraySchema enumSchema = new ArraySchema().items( + new ArraySchema().items( + new StringSchema().addEnumItem("Aaaa").addEnumItem("Bbbb"))); + final Schema model = new Schema().type("object").addProperties("name", enumSchema); + + final DefaultCodegen codegen = new ConfluenceWikiCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.dataType, "array[array[String]]"); + Assert.assertEquals(enumVar.datatypeWithEnum, "array[array[String]]"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, "null"); + Assert.assertEquals(enumVar.baseType, "array"); + Assert.assertTrue(enumVar.isEnum); + + Assert.assertEquals(enumVar.mostInnerItems.baseName, "name"); + Assert.assertEquals(enumVar.mostInnerItems.dataType, "String"); + Assert.assertEquals(enumVar.mostInnerItems.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.mostInnerItems.name, "name"); + Assert.assertEquals(enumVar.mostInnerItems.defaultValue, "null"); + Assert.assertEquals(enumVar.mostInnerItems.baseType, "string"); + + Assert.assertEquals(enumVar.mostInnerItems.baseType, enumVar.items.items.baseType); + } + + @Test(description = "not override identical parent enums") + public void overrideEnumTest() { + final StringSchema identicalEnumProperty = new StringSchema(); + identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + + final StringSchema subEnumProperty = new StringSchema(); + subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); + + // Add one enum property to the parent + final Map parentProperties = new HashMap<>(); + parentProperties.put("sharedThing", identicalEnumProperty); + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + final Map subProperties = new HashMap<>(); + subProperties.put("unsharedThing", subEnumProperty); + + final Schema parentModel = new Schema(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + Discriminator discriminator = new Discriminator().mapping("name", StringUtils.EMPTY); + discriminator.setPropertyName("model_type"); + parentModel.setDiscriminator(discriminator); + + final ComposedSchema composedSchema = new ComposedSchema() + .addAllOfItem(new Schema().$ref(parentModel.getName())); + composedSchema.setName("sample"); + + final ConfluenceWikiCodegen codegen = new ConfluenceWikiCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + openAPI.setComponents(new Components() + .addSchemas(parentModel.getName(), parentModel) + .addSchemas(composedSchema.getName(), composedSchema) + ); + + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", composedSchema); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "ParentModel"); + Assert.assertTrue(cm.imports.contains("ParentModel")); + } + + @Test + public void testEnumTestSchema() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + ConfluenceWikiCodegen codegen = new ConfluenceWikiCodegen(); + codegen.setOpenAPI(openAPI); + + Schema enumTest = openAPI.getComponents().getSchemas().get("Enum_Test"); + Assert.assertNotNull(enumTest); + CodegenModel cm = codegen.fromModel("Enum_Test", enumTest); + + Assert.assertEquals(cm.getVars().size(), 8); + CodegenProperty cp0 = cm.getVars().get(0); + Assert.assertEquals(cp0.dataType, "String"); + CodegenProperty cp1 = cm.getVars().get(1); + Assert.assertEquals(cp1.dataType, "String"); + CodegenProperty cp2 = cm.getVars().get(2); + Assert.assertEquals(cp2.dataType, "Integer"); + CodegenProperty cp3 = cm.getVars().get(3); + Assert.assertEquals(cp3.dataType, "Double"); + CodegenProperty cp4 = cm.getVars().get(4); + Assert.assertEquals(cp4.dataType, "OuterEnum"); + CodegenProperty cp5 = cm.getVars().get(5); + Assert.assertEquals(cp5.dataType, "OuterEnumInteger"); + CodegenProperty cp6 = cm.getVars().get(6); + Assert.assertEquals(cp6.dataType, "OuterEnumDefaultValue"); + CodegenProperty cp7 = cm.getVars().get(7); + Assert.assertEquals(cp7.dataType, "OuterEnumIntegerDefaultValue"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpNetCoreClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpNetCoreClientCodegenTest.java new file mode 100644 index 00000000000..0d28f8f255a --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpNetCoreClientCodegenTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2020 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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 + * + * https://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.csharp; + +import org.openapitools.codegen.languages.CSharpNetCoreClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class CSharpNetCoreClientCodegenTest { + + @Test + public void testToEnumVarName() throws Exception { + final CSharpNetCoreClientCodegen codegen = new CSharpNetCoreClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.toEnumVarName("FooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("fooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo-bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo_bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo bar", "string"), "FooBar"); + + // The below cases do not work currently, camelize doesn't support uppercase + // Assert.assertEquals(codegen.toEnumVarName("FOO-BAR", "string"), "FooBar"); + // Assert.assertEquals(codegen.toEnumVarName("FOO_BAR", "string"), "FooBar"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java index cab086ffaf1..c8438e80a0f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java @@ -22,6 +22,7 @@ import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.*; import org.openapitools.codegen.*; import org.openapitools.codegen.languages.DartClientCodegen; +import org.openapitools.codegen.languages.DartDioClientCodegen; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -521,4 +522,29 @@ public class DartModelTest { Assert.assertEquals(op.returnType, "DateTime"); Assert.assertEquals(op.bodyParam.dataType, "DateTime"); } + + @Test(description = "correctly generate date/datetime default values, currently null") + public void dateDefaultValues() { + final DateSchema date = new DateSchema(); + date.setDefault("2021-01-01"); + final DateTimeSchema dateTime = new DateTimeSchema(); + dateTime.setDefault("2021-01-01T14:00:00Z"); + final Schema model = new Schema() + .description("a sample model") + .addProperties("date", date) + .addProperties("dateTime", dateTime) + .addProperties("mapNoDefault", new MapSchema()); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty dateDefault = cm.vars.get(0); + Assert.assertEquals(dateDefault.name, "date"); + Assert.assertNull(dateDefault.defaultValue); + + final CodegenProperty dateTimeDefault = cm.vars.get(1); + Assert.assertEquals(dateTimeDefault.name, "dateTime"); + Assert.assertNull(dateTimeDefault.defaultValue); + } } 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 index ade2bff57c0..3faa4d477a0 100644 --- 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 @@ -391,4 +391,56 @@ public class DartDioModelTest { Assert.assertEquals(cm.name, name); Assert.assertEquals(cm.classname, expectedName); } + + @Test(description = "correctly generate collection default values") + public void collectionDefaultValues() { + final ArraySchema array = new ArraySchema(); + array.setDefault("[]"); + final Schema model = new Schema() + .description("a sample model") + .addProperties("arrayNoDefault", new ArraySchema()) + .addProperties("arrayEmptyDefault", array) + .addProperties("mapNoDefault", new MapSchema()); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty arrayNoDefault = cm.vars.get(0); + Assert.assertEquals(arrayNoDefault.name, "arrayNoDefault"); + Assert.assertNull(arrayNoDefault.defaultValue); + + final CodegenProperty arrayEmptyDefault = cm.vars.get(1); + Assert.assertEquals(arrayEmptyDefault.name, "arrayEmptyDefault"); + Assert.assertEquals(arrayEmptyDefault.defaultValue, "ListBuilder()"); + + final CodegenProperty mapNoDefault = cm.vars.get(2); + Assert.assertEquals(mapNoDefault.name, "mapNoDefault"); + Assert.assertNull(mapNoDefault.defaultValue); + } + + @Test(description = "correctly generate date/datetime default values, currently null") + public void dateDefaultValues() { + final DateSchema date = new DateSchema(); + date.setDefault("2021-01-01"); + final DateTimeSchema dateTime = new DateTimeSchema(); + dateTime.setDefault("2021-01-01T14:00:00Z"); + final Schema model = new Schema() + .description("a sample model") + .addProperties("date", date) + .addProperties("dateTime", dateTime) + .addProperties("mapNoDefault", new MapSchema()); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty dateDefault = cm.vars.get(0); + Assert.assertEquals(dateDefault.name, "date"); + Assert.assertNull(dateDefault.defaultValue); + + final CodegenProperty dateTimeDefault = cm.vars.get(1); + Assert.assertEquals(dateTimeDefault.name, "dateTime"); + Assert.assertNull(dateTimeDefault.defaultValue); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ktorm/KtormSchemaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ktorm/KtormSchemaCodegenTest.java new file mode 100644 index 00000000000..6accc27c9ce --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ktorm/KtormSchemaCodegenTest.java @@ -0,0 +1,316 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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 + * + * https://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.ktorm; + +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.KtormSchemaCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class KtormSchemaCodegenTest { + + private Map toObjs(CodegenModel cm) { + Map objs = new HashMap(); + List models = new ArrayList(); + Map model = new HashMap<>(); + model.put("model", cm); + models.add(model); + objs.put("models", models); + return objs; + } + + private CodegenModel getModel(Schema schema, String pkName, Boolean surrogateKey) { + final KtormSchemaCodegen codegen = new KtormSchemaCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); + codegen.setAddSurrogateKey(surrogateKey); + codegen.setPrimaryKeyConvention(pkName); + codegen.setOpenAPI(openAPI); + CodegenModel cm = codegen.fromModel("sample", schema); + codegen.postProcessModels(toObjs(cm)); + return cm; + } + + private Map getExtension(CodegenProperty property) { + return (Map) + property.vendorExtensions.get(KtormSchemaCodegen.VENDOR_EXTENSION_SCHEMA); + } + + private Map getColumnDefinition(Map schema) { + return (Map) + schema.get("columnDefinition"); + } + + private Map getRelationDefinition(Map schema) { + return (Map) + schema.get("relationDefinition"); + } + + private Map getKtormSchema(Schema propertySchema) { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("key", propertySchema) + .addRequiredItem("key"); + final CodegenModel cm = getModel(schema, "id", false); + final CodegenProperty prop = cm.vars.get(0); + return getExtension(prop); + } + + private String getMatchedColType(Schema propertySchema) { + Map ktormSchema = getColumnDefinition(getKtormSchema(propertySchema)); + return (String) ktormSchema.get("colType"); + } + + private String getMatchedKotlinType(Schema propertySchema) { + Map ktormSchema = getColumnDefinition(getKtormSchema(propertySchema)); + return (String) ktormSchema.get("colKotlinType"); + } + + private String getMatchedRelation(Schema propertySchema) { + Map ktormSchema = getRelationDefinition(getKtormSchema(propertySchema)); + if (ktormSchema == null) return null; + return (String) ktormSchema.get("fkName"); + } + + @Test + public void testMatchedColType() { + Assert.assertEquals(getMatchedColType(new StringSchema()), "text"); + Assert.assertEquals(getMatchedColType(new StringSchema().type("char")), "text"); + Assert.assertEquals(getMatchedColType(new StringSchema().format("char")), "text"); + Assert.assertEquals(getMatchedColType(new BooleanSchema()), "boolean"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().type("short")), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().format("short")), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema()), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().type("integer")), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().format("integer")), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), "int"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().type("long")), "long"); + Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), "long"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), "float"); + Assert.assertEquals(getMatchedColType(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), "float"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), "double"); + Assert.assertEquals(getMatchedColType(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), "double"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), "float"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), "double"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("real")), "double"); + Assert.assertEquals(getMatchedColType(new NumberSchema().format("real")), "decimal"); + Assert.assertEquals(getMatchedColType(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), "decimal"); + Assert.assertEquals(getMatchedColType(new NumberSchema().type("decimal")), "decimal"); + Assert.assertEquals(getMatchedColType(new NumberSchema().type("BigDecimal")), "decimal"); + Assert.assertEquals(getMatchedColType(new ByteArraySchema()), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT))), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema()), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("list")), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("set")), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("map")), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema()), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("binary")), "blob"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("AnyType")), "blob"); + Assert.assertEquals(getMatchedColType(new BinarySchema()), "blob"); + Assert.assertEquals(getMatchedColType(new FileSchema()), "blob"); + Assert.assertEquals(getMatchedColType(new DateSchema()), "date"); + Assert.assertEquals(getMatchedColType(new DateTimeSchema()), "datetime"); + Assert.assertEquals(getMatchedColType(new UUIDSchema()), "text"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("UUID")), "text"); + Assert.assertEquals(getMatchedColType(new StringSchema().format("URI")), "text"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("URI")), "text"); + Assert.assertEquals(getMatchedColType(new StringSchema().format("password")), "text"); + Assert.assertEquals(getMatchedColType(new StringSchema().type("password")), "text"); + } + + @Test + public void testMatchedColKotlinType() { + // *1 - format specifiers aren't used + Assert.assertEquals(getMatchedKotlinType(new StringSchema()), "kotlin.String"); + Assert.assertEquals(getMatchedKotlinType(new StringSchema().type("char")), "kotlin.String"); + Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("char")), "kotlin.String"); + Assert.assertEquals(getMatchedKotlinType(new BooleanSchema()), "kotlin.Boolean"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), "kotlin.Byte"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), "kotlin.Int"); //*1 + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("short")), "kotlin.Short"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format("short")), "kotlin.Int"); //*1 + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema()), "kotlin.Int"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("integer")), "kotlin.Int"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format("integer")), "kotlin.Int"); //*1 + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), "kotlin.Int"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("long")), "kotlin.Long"); + Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), "kotlin.Long"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Float"); + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Float"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Double"); + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Double"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Float"); //*1 + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Double"); //*1 + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("real")), "kotlin.Double"); + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format("real")), "java.math.BigDecimal"); //*1 + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), "java.math.BigDecimal"); + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type("decimal")), "java.math.BigDecimal"); + Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type("BigDecimal")), "java.math.BigDecimal"); + Assert.assertEquals(getMatchedKotlinType(new ByteArraySchema()), "kotlin.ByteArray"); + Assert.assertEquals(getMatchedKotlinType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "kotlin.Array"); + Assert.assertEquals(getMatchedKotlinType(new ArraySchema().items(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT))), "kotlin.Array"); //*1 + Assert.assertEquals(getMatchedKotlinType(new ArraySchema()), "kotlin.Array"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("list")), "kotlin.collections.List"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("set")), "kotlin.collections.Set"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("map")), "kotlin.collections.Map"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema()), "kotlin.Any"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("binary")), "kotlin.ByteArray"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("AnyType")), "kotlin.Any"); + Assert.assertEquals(getMatchedKotlinType(new BinarySchema()), "java.io.File"); //looks like a bug + Assert.assertEquals(getMatchedKotlinType(new FileSchema()), "java.io.File"); + Assert.assertEquals(getMatchedKotlinType(new DateSchema()), "java.time.LocalDate"); + Assert.assertEquals(getMatchedKotlinType(new DateTimeSchema()), "java.time.LocalDateTime"); + Assert.assertEquals(getMatchedKotlinType(new UUIDSchema()), "java.util.UUID"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("UUID")), "java.util.UUID"); + Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("URI")), "java.net.URI"); + Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("URI")), "java.net.URI"); + Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("password")), "kotlin.String"); + Assert.assertEquals(getMatchedKotlinType(new StringSchema().type("password")), "kotlin.String"); + } + + @Test + public void testNonMatchedRelation() { + Assert.assertEquals(getMatchedRelation(new StringSchema()), null); + Assert.assertEquals(getMatchedRelation(new StringSchema().type("char")), null); + Assert.assertEquals(getMatchedRelation(new StringSchema().format("char")), null); + Assert.assertEquals(getMatchedRelation(new BooleanSchema()), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("short")), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().format("short")), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema()), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("integer")), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().format("integer")), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("long")), null); + Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("real")), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().format("real")), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().type("decimal")), null); + Assert.assertEquals(getMatchedRelation(new NumberSchema().type("BigDecimal")), null); + Assert.assertEquals(getMatchedRelation(new ByteArraySchema()), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("list")), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("set")), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("map")), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema()), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("binary")), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("AnyType")), null); + Assert.assertEquals(getMatchedRelation(new BinarySchema()), null); + Assert.assertEquals(getMatchedRelation(new FileSchema()), null); + Assert.assertEquals(getMatchedRelation(new DateSchema()), null); + Assert.assertEquals(getMatchedRelation(new DateTimeSchema()), null); + Assert.assertEquals(getMatchedRelation(new UUIDSchema()), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("UUID")), null); + Assert.assertEquals(getMatchedRelation(new StringSchema().format("URI")), null); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("URI")), null); + Assert.assertEquals(getMatchedRelation(new StringSchema().format("password")), null); + Assert.assertEquals(getMatchedRelation(new StringSchema().type("password")), null); + } + + @Test + public void testMatchedRelation() { + //foreign keys + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("Something")), "something"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("Something")), "long"); + Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("UserNamespace.UserClass")), "userNamespaceUserClass"); + Assert.assertEquals(getMatchedColType(new ObjectSchema().type("UserNamespace.UserClass")), "long"); + //arrays are special case, we convert them to 1:N relations + Assert.assertEquals(getMatchedRelation(new ArraySchema()), "key"); + Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new ObjectSchema().type("Something"))), "something"); + Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new ObjectSchema().type("UserNamespace.UserClass"))), "userNamespaceUserClass"); + Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "key"); + Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new StringSchema())), "key"); + //blob will be the default type, the template shouldn't include those fields + Assert.assertEquals(getMatchedColType(new ArraySchema()), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new ObjectSchema().type("Something"))), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new ObjectSchema().type("UserNamespace.UserClass"))), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "blob"); + Assert.assertEquals(getMatchedColType(new ArraySchema().items(new StringSchema())), "blob"); + } + + @Test + public void testDefinePrimaryKey() { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("key" , new IntegerSchema()) + .addRequiredItem("key"); + CodegenModel cm = getModel(schema, "key", false); + Assert.assertEquals(cm.vars.size(), 1); + CodegenProperty prop = cm.vars.get(0); + Map propSchema = getColumnDefinition(getExtension(prop)); + Assert.assertEquals(propSchema.get("colPrimaryKey"), true); + Assert.assertEquals(propSchema.get("colType"), "int"); + } + + @Test + public void testDontAddSorrogateKey() { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("key" , new IntegerSchema()) + .addRequiredItem("key"); + CodegenModel cm = getModel(schema, "id", false); + Assert.assertEquals(cm.vars.size(), 1); + CodegenProperty prop = cm.vars.get(0); + Map propSchema = getColumnDefinition(getExtension(prop)); + Assert.assertEquals(propSchema.get("colPrimaryKey"), false); + Assert.assertEquals(propSchema.get("colType"), "int"); + } + + @Test + public void testAddSorrogateKey() { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("key", new IntegerSchema()); + CodegenModel cm = getModel(schema, "id", true); + Assert.assertEquals(cm.vars.size(), 2); + CodegenProperty prop = cm.vars.get(0); + Map propSchema = getColumnDefinition(getExtension(prop)); + Assert.assertEquals(propSchema.get("colNotNull"), true); + Assert.assertEquals(propSchema.get("colPrimaryKey"), true); + Assert.assertEquals(propSchema.get("colName"), "id"); + Assert.assertEquals(propSchema.get("colType"), "long"); //by default + CodegenProperty prop2 = cm.vars.get(1); + Map propSchema2 = getColumnDefinition(getExtension(prop2)); + Assert.assertEquals(propSchema2.get("colNotNull"), false); + Assert.assertEquals(propSchema2.get("colPrimaryKey"), false); + Assert.assertEquals(propSchema2.get("colName"), "key"); + Assert.assertEquals(propSchema2.get("colType"), "int"); + + } + +} 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 51049743954..eb8d90a468b 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 @@ -34,8 +34,8 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; - private static final String NMP_VERSION = "1.1.2"; + private static final String NPM_NAME = "npmName"; + private static final String NPM_VERSION = "1.1.2"; private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String NG_VERSION = "2"; @@ -44,6 +44,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String API_MODULE_PREFIX = ""; public static final String CONFIGURATION_PREFIX = ""; public static final String QUERY_PARAM_OBJECT_FORMAT_VALUE = "dot"; + public static final String PROVIDED_IN_LEVEL = "root"; public static String SERVICE_SUFFIX = "Service"; public static String SERVICE_FILE_SUFFIX = ".service"; public static String MODEL_SUFFIX = ""; @@ -66,12 +67,13 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { .put(AbstractTypeScriptClientCodegen.NULL_SAFE_ADDITIONAL_PROPS, NULL_SAFE_ADDITIONAL_PROPS_VALUE) .put(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX) .put(TypeScriptAngularClientCodegen.STRING_ENUMS, STRING_ENUMS_VALUE) - .put(TypeScriptAngularClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptAngularClientCodegen.NPM_VERSION, NMP_VERSION) + .put(TypeScriptAngularClientCodegen.NPM_NAME, NPM_NAME) + .put(TypeScriptAngularClientCodegen.NPM_VERSION, NPM_VERSION) .put(TypeScriptAngularClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.USE_SINGLE_REQUEST_PARAMETER, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.PROVIDED_IN_ROOT, Boolean.FALSE.toString()) + .put(TypeScriptAngularClientCodegen.PROVIDED_IN, PROVIDED_IN_LEVEL) .put(TypeScriptAngularClientCodegen.TAGGED_UNIONS, Boolean.FALSE.toString()) .put(TypeScriptAngularClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) .put(TypeScriptAngularClientCodegen.NG_VERSION, NG_VERSION) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java index 683d4aa4b02..98f06e7b889 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java @@ -15,6 +15,18 @@ */ package org.openapitools.codegen.python; +import com.google.common.io.Resources; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.Paths; +import io.swagger.v3.oas.models.parameters.RequestBody; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import javax.validation.constraints.AssertTrue; +import org.apache.commons.io.IOUtils; import org.openapitools.codegen.config.CodegenConfigurator; import com.google.common.collect.Sets; @@ -33,6 +45,7 @@ import org.openapitools.codegen.*; import org.openapitools.codegen.languages.PythonClientCodegen; import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; +import org.testng.TestNGAntTask.Mode; import org.testng.annotations.Test; @SuppressWarnings("static-method") @@ -425,4 +438,31 @@ public class PythonClientTest { final CodegenModel model = codegen.fromModel(modelName, modelSchema); Assert.assertEquals((int) model.getMinProperties(), 1); } + + @Test(description = "tests RecursiveToExample") + public void testRecursiveToExample() throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_8052_recursive_model.yaml"); + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.setOpenAPI(openAPI); + + final Operation operation = openAPI.getPaths().get("/geojson").getPost(); + Schema schema = ModelUtils.getSchemaFromRequestBody(operation.getRequestBody()); + String exampleValue = codegen.toExampleValue(schema, null); + + // uncomment if you need to regenerate the expected value + // PrintWriter printWriter = new PrintWriter("src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt"); + // printWriter.write(exampleValue); + // printWriter.close(); + // org.junit.Assert.assertTrue(false); + + String expectedValue = Resources.toString( + Resources.getResource("3_0/issue_8052_recursive_model_expected_value.txt"), + StandardCharsets.UTF_8); + expectedValue = expectedValue.replaceAll("\\r\\n", "\n"); + + + Assert.assertEquals(expectedValue.trim(), exampleValue.trim()); + + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java index d4a8efebae5..2001a9844c5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java @@ -11,6 +11,7 @@ public class StringUtilsTest { public void testUnderscore() { Assert.assertEquals(underscore("abcd"), "abcd"); Assert.assertEquals(underscore("abCd"), "ab_cd"); + Assert.assertEquals(underscore("ListABCs"), "list_abcs"); } @Test diff --git a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml index 505aa0dd631..c37f4329e4e 100644 --- a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1086,6 +1086,7 @@ definitions: xml: name: Order Category: + x-swift-hashable: true type: object required: - name @@ -1124,6 +1125,7 @@ definitions: xml: name: User Tag: + x-swift-hashable: true type: object properties: id: diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model.yaml new file mode 100644 index 00000000000..6d833b29211 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model.yaml @@ -0,0 +1,83 @@ +openapi: 3.0.0 +info: + version: 01.01.00 + title: APITest API documentation. + termsOfService: http://api.apitest.com/party/tos/ +servers: + - url: https://api.apitest.com/v1 +paths: + /geojson: + post: + summary: Add a GeoJson Object + operationId: post-geojson + responses: + '201': + description: Created + content: + application/json: + schema: + type: string + description: GeoJson ID + '400': + description: Bad Request + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/GeoJsonGeometry' + parameters: [] +components: + schemas: + GeoJsonGeometry: + title: GeoJsonGeometry + description: GeoJSON geometry + oneOf: + - $ref: '#/components/schemas/Point' + - $ref: '#/components/schemas/GeometryCollection' + discriminator: + propertyName: type + mapping: + Point: '#/components/schemas/Point' + GeometryCollection: '#/components/schemas/GeometryCollection' + externalDocs: + url: http://geojson.org/geojson-spec.html#geometry-objects + Point: + title: Point + type: object + description: GeoJSON geometry + externalDocs: + url: http://geojson.org/geojson-spec.html#id2 + properties: + coordinates: + title: Point3D + type: array + description: Point in 3D space + externalDocs: + url: http://geojson.org/geojson-spec.html#id2 + minItems: 2 + maxItems: 3 + items: + type: number + format: double + type: + type: string + default: Point + required: + - type + GeometryCollection: + title: GeometryCollection + type: object + description: GeoJSon geometry collection + required: + - type + - geometries + externalDocs: + url: http://geojson.org/geojson-spec.html#geometrycollection + properties: + type: + type: string + default: GeometryCollection + geometries: + type: array + items: + $ref: '#/components/schemas/GeoJsonGeometry' diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt b/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt new file mode 100644 index 00000000000..98ef62651fb --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt @@ -0,0 +1,9 @@ +GeoJsonGeometry( + type="GeometryCollection", + geometries=[ + GeoJsonGeometry( + type="GeometryCollection", + geometries=[], + ), + ], + ) \ No newline at end of file diff --git a/mvnw b/mvnw index 4e574d9a02d..41c0f0c23db 100755 --- a/mvnw +++ b/mvnw @@ -8,7 +8,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script +# Maven Start Up Batch script # # Required ENV vars: # ------------------ @@ -114,7 +114,6 @@ if $mingw ; then M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then @@ -200,6 +199,85 @@ if [ -z "$BASE_DIR" ]; then exit 1; fi +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} if [ "$MVNW_VERBOSE" = true ]; then echo $MAVEN_PROJECTBASEDIR @@ -218,6 +296,11 @@ if $cygwin; then MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` fi +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain exec "$JAVACMD" \ diff --git a/mvnw.cmd b/mvnw.cmd index e506408e362..86115719e53 100755 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -7,7 +7,7 @@ @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM -@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM http://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @@ -18,7 +18,7 @@ @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script +@REM Maven Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @@ -26,7 +26,7 @@ @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @@ -37,7 +37,7 @@ @echo off @REM set title of command window title %0 -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME @@ -117,10 +117,47 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end diff --git a/pom.xml b/pom.xml index f2a7a0800a5..9f2b516426a 100644 --- a/pom.xml +++ b/pom.xml @@ -1181,6 +1181,7 @@ + samples/client/petstore/crystal samples/server/petstore/python-aiohttp samples/server/petstore/python-aiohttp-srclayout @@ -1429,9 +1430,26 @@ + + samples/client/petstore/swift5/alamofireLibrary + samples/client/petstore/swift5/combineLibrary + samples/client/petstore/swift5/default + samples/client/petstore/swift5/deprecated + samples/client/petstore/swift5/nonPublicApi + samples/client/petstore/swift5/objcCompatible + samples/client/petstore/swift5/promisekitLibrary + samples/client/petstore/swift5/readonlyProperties + samples/client/petstore/swift5/resultLibrary + samples/client/petstore/swift5/rxswiftLibrary + samples/client/petstore/swift5/urlsessionLibrary + + samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests + samples/client/petstore/swift5/combineLibrary/SwaggerClientTests samples/client/petstore/swift5/default/SwaggerClientTests - samples/client/petstore/swift5/promisekit/SwaggerClientTests - samples/client/petstore/swift5/rxswift/SwaggerClientTests + samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests + samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests + samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests + samples/client/petstore/swift4/default/SwaggerClientTests samples/client/petstore/swift4/promisekit/SwaggerClientTests samples/client/petstore/swift4/rxswift/SwaggerClientTests diff --git a/samples/client/petstore/crystal/.gitignore b/samples/client/petstore/crystal/.gitignore new file mode 100644 index 00000000000..05a17cb8f0a --- /dev/null +++ b/samples/client/petstore/crystal/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/client/petstore/crystal/.openapi-generator-ignore b/samples/client/petstore/crystal/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/crystal/.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/crystal/.openapi-generator/FILES b/samples/client/petstore/crystal/.openapi-generator/FILES new file mode 100644 index 00000000000..aa17a1e4b98 --- /dev/null +++ b/samples/client/petstore/crystal/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +.travis.yml +README.md +git_push.sh +shard.yml +spec/spec_helper.cr +src/petstore.cr +src/petstore/api/pet_api.cr +src/petstore/api/store_api.cr +src/petstore/api/user_api.cr +src/petstore/api_client.cr +src/petstore/api_error.cr +src/petstore/configuration.cr +src/petstore/models/api_response.cr +src/petstore/models/category.cr +src/petstore/models/order.cr +src/petstore/models/pet.cr +src/petstore/models/tag.cr +src/petstore/models/user.cr diff --git a/samples/client/petstore/crystal/.openapi-generator/VERSION b/samples/client/petstore/crystal/.openapi-generator/VERSION new file mode 100644 index 00000000000..c30f0ec2be7 --- /dev/null +++ b/samples/client/petstore/crystal/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/crystal/.rspec b/samples/client/petstore/crystal/.rspec new file mode 100644 index 00000000000..83e16f80447 --- /dev/null +++ b/samples/client/petstore/crystal/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/client/petstore/crystal/.rubocop.yml b/samples/client/petstore/crystal/.rubocop.yml new file mode 100644 index 00000000000..d32b2b1cdab --- /dev/null +++ b/samples/client/petstore/crystal/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/samples/client/petstore/crystal/.travis.yml b/samples/client/petstore/crystal/.travis.yml new file mode 100644 index 00000000000..b66a6b55820 --- /dev/null +++ b/samples/client/petstore/crystal/.travis.yml @@ -0,0 +1,16 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +language: crystal + +script: + - crystal spec +# uncomment below to check the code format +# - crystal tool format --check diff --git a/samples/client/petstore/crystal/README.md b/samples/client/petstore/crystal/README.md new file mode 100644 index 00000000000..fc7fa03548c --- /dev/null +++ b/samples/client/petstore/crystal/README.md @@ -0,0 +1,38 @@ +# petstore + +The Crystsal module for the 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. + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CrystalClientCodegen + +## Installation + +### Install from Git + +Add the following to shard.yaml + +```yaml +dependencies: + petstore: + github: GIT_USER_ID/GIT_REPO_ID + version: ~> 1.0.0 +``` + +## Development + +Install dependencies + +```shell +shards +``` + +Run the tests: + +```shell +crystal spec +``` diff --git a/samples/client/petstore/crystal/bin/ameba b/samples/client/petstore/crystal/bin/ameba new file mode 100755 index 00000000000..332b8c750a4 Binary files /dev/null and b/samples/client/petstore/crystal/bin/ameba differ diff --git a/samples/client/petstore/crystal/bin/ameba.cr b/samples/client/petstore/crystal/bin/ameba.cr new file mode 100644 index 00000000000..d61d0ff11a5 --- /dev/null +++ b/samples/client/petstore/crystal/bin/ameba.cr @@ -0,0 +1,7 @@ +# Require ameba cli which starts the inspection. +require "ameba/cli" + +# Require ameba extensions here which are added as project dependencies. +# Example: +# +# require "ameba-performance" diff --git a/samples/client/petstore/crystal/git_push.sh b/samples/client/petstore/crystal/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/crystal/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/crystal/pom.xml b/samples/client/petstore/crystal/pom.xml new file mode 100644 index 00000000000..f4b890f7d80 --- /dev/null +++ b/samples/client/petstore/crystal/pom.xml @@ -0,0 +1,56 @@ + + 4.0.0 + org.openapitools + CrystalPetstoreClientTests + pom + 1.0-SNAPSHOT + Crystal OpenAPI Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + + shards-install + pre-integration-test + + exec + + + shards + + + + crystal-spec + integration-test + + exec + + + crystal + + spec + + + + + + + + diff --git a/samples/client/petstore/crystal/shard.lock b/samples/client/petstore/crystal/shard.lock new file mode 100644 index 00000000000..97567adcb9e --- /dev/null +++ b/samples/client/petstore/crystal/shard.lock @@ -0,0 +1,34 @@ +version: 2.0 +shards: + ameba: + git: https://github.com/crystal-ameba/ameba.git + version: 0.13.3 + + crest: + git: https://github.com/mamantoha/crest.git + version: 0.26.1 + + exception_page: + git: https://github.com/crystal-loot/exception_page.git + version: 0.1.4 + + http-client-digest_auth: + git: https://github.com/mamantoha/http-client-digest_auth.git + version: 0.4.0 + + http_proxy: + git: https://github.com/mamantoha/http_proxy.git + version: 0.7.2 + + kemal: + git: https://github.com/kemalcr/kemal.git + version: 0.27.0 + + kilt: + git: https://github.com/jeromegn/kilt.git + version: 0.4.0 + + radix: + git: https://github.com/luislavena/radix.git + version: 0.3.9 + diff --git a/samples/client/petstore/crystal/shard.yml b/samples/client/petstore/crystal/shard.yml new file mode 100644 index 00000000000..06fc3300e05 --- /dev/null +++ b/samples/client/petstore/crystal/shard.yml @@ -0,0 +1,20 @@ +name: Petstore +version: 1.0.0 +authors: + - +description: | + - +crystal: ">= 0.35.1" +dependencies: + crest: + github: mamantoha/crest + version: ~> 0.26.0 + +development_dependencies: + kemal: + github: kemalcr/kemal + version: ~>0.27.0 + ameba: + github: crystal-ameba/ameba + +license: diff --git a/samples/client/petstore/crystal/spec/api/pet_api_spec.cr b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr new file mode 100644 index 00000000000..23bdfa81847 --- /dev/null +++ b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr @@ -0,0 +1,137 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::PetApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe "PetApi" do + describe "test an instance of PetApi" do + it "should create an instance of PetApi" do + api_instance = Petstore::PetApi.new + # TODO expect(api_instance).to be_instance_of(Petstore::PetApi) + end + end + + # unit tests for add_pet + # Add a new pet to the store + # @param pet Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [Pet] + describe "add_pet test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for delete_pet + # Deletes a pet + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [nil] + describe "delete_pet test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for find_pets_by_status + # 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 + # @param [Hash] opts the optional parameters + # @return [Array(Pet)] + describe "find_pets_by_status test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for find_pets_by_tags + # 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 + # @param [Hash] opts the optional parameters + # @return [Array(Pet)] + describe "find_pets_by_tags test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for get_pet_by_id + # Find pet by ID + # Returns a single pet + # @param pet_id ID of pet to return + # @param [Hash] opts the optional parameters + # @return [Pet] + describe "get_pet_by_id test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + api_instance = Petstore::PetApi.new + # create a pet to start with + pet_id = Int64.new(91829) + pet = Petstore::Pet.new(id: pet_id, category: Petstore::Category.new(id: pet_id + 10, name: "crystal category"), name: "crystal", photo_urls: ["https://crystal-lang.org"], tags: [Petstore::Tag.new(id: pet_id + 100, name: "crystal tag")], status: "available") + + api_instance.add_pet(pet) + + result = api_instance.get_pet_by_id(pet_id: pet_id) + result.id.should eq pet_id + result.category.id.should eq pet_id + 10 + result.category.name.should eq "crystal category" + result.name.should eq "crystal" + result.photo_urls.should eq ["https://crystal-lang.org"] + result.status.should eq "available" + result.tags[0].id.should eq pet_id + 100 + end + end + + # unit tests for update_pet + # Update an existing pet + # @param pet Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [Pet] + describe "update_pet test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for update_pet_with_form + # Updates a pet in the store with form data + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [nil] + describe "update_pet_with_form test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for upload_file + # uploads an image + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [ApiResponse] + describe "upload_file test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/api/store_api_spec.cr b/samples/client/petstore/crystal/spec/api/store_api_spec.cr new file mode 100644 index 00000000000..592747d6fe7 --- /dev/null +++ b/samples/client/petstore/crystal/spec/api/store_api_spec.cr @@ -0,0 +1,72 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::StoreApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe "StoreApi" do + describe "test an instance of StoreApi" do + it "should create an instance of StoreApi" do + api_instance = Petstore::StoreApi.new + # TODO expect(api_instance).to be_instance_of(Petstore::StoreApi) + end + end + + # unit tests for delete_order + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe "delete_order test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for get_inventory + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Hash(String, Int32)] + describe "get_inventory test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for get_order_by_id + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Order] + describe "get_order_by_id test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for place_order + # Place an order for a pet + # @param order order placed for purchasing the pet + # @param [Hash] opts the optional parameters + # @return [Order] + describe "place_order test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/api/user_api_spec.cr b/samples/client/petstore/crystal/spec/api/user_api_spec.cr new file mode 100644 index 00000000000..38a13b9d7c9 --- /dev/null +++ b/samples/client/petstore/crystal/spec/api/user_api_spec.cr @@ -0,0 +1,118 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::UserApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe "UserApi" do + describe "test an instance of UserApi" do + it "should create an instance of UserApi" do + api_instance = Petstore::UserApi.new + # TODO expect(api_instance).to be_instance_of(Petstore::UserApi) + end + end + + # unit tests for create_user + # Create user + # This can only be done by the logged in user. + # @param user Created user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe "create_user test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for create_users_with_array_input + # Creates list of users with given input array + # @param user List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe "create_users_with_array_input test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for create_users_with_list_input + # Creates list of users with given input array + # @param user List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe "create_users_with_list_input test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for delete_user + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe "delete_user test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for get_user_by_name + # Get user by user name + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [User] + describe "get_user_by_name test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for login_user + # Logs user into the system + # @param username The user name for login + # @param password The password for login in clear text + # @param [Hash] opts the optional parameters + # @return [String] + describe "login_user test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for logout_user + # Logs out current logged in user session + # @param [Hash] opts the optional parameters + # @return [nil] + describe "logout_user test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + # unit tests for update_user + # Updated user + # This can only be done by the logged in user. + # @param username name that need to be deleted + # @param user Updated user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe "update_user test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/api_response_spec.cr b/samples/client/petstore/crystal/spec/models/api_response_spec.cr new file mode 100644 index 00000000000..3a4ff0b1269 --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/api_response_spec.cr @@ -0,0 +1,44 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::ApiResponse +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ApiResponse do + + describe "test an instance of ApiResponse" do + it "should create an instance of ApiResponse" do + #instance = Petstore::ApiResponse.new + #expect(instance).to be_instance_of(Petstore::ApiResponse) + end + end + describe "test attribute 'code'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute '_type'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'message'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/category_spec.cr b/samples/client/petstore/crystal/spec/models/category_spec.cr new file mode 100644 index 00000000000..120fa0459f1 --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/category_spec.cr @@ -0,0 +1,38 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::Category +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Category do + + describe "test an instance of Category" do + it "should create an instance of Category" do + #instance = Petstore::Category.new + #expect(instance).to be_instance_of(Petstore::Category) + end + end + describe "test attribute 'id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'name'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/order_spec.cr b/samples/client/petstore/crystal/spec/models/order_spec.cr new file mode 100644 index 00000000000..e64ada1fb51 --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/order_spec.cr @@ -0,0 +1,66 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::Order +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Order do + + describe "test an instance of Order" do + it "should create an instance of Order" do + #instance = Petstore::Order.new + #expect(instance).to be_instance_of(Petstore::Order) + end + end + describe "test attribute 'id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'pet_id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'quantity'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'ship_date'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'status'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + # validator = Petstore::EnumTest::EnumAttributeValidator.new("String", ["placed", "approved", "delivered"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + + describe "test attribute 'complete'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/pet_spec.cr b/samples/client/petstore/crystal/spec/models/pet_spec.cr new file mode 100644 index 00000000000..d3eaf60dfc1 --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/pet_spec.cr @@ -0,0 +1,66 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::Pet +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Pet do + + describe "test an instance of Pet" do + it "should create an instance of Pet" do + #instance = Petstore::Pet.new + #expect(instance).to be_instance_of(Petstore::Pet) + end + end + describe "test attribute 'id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'category'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'name'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'photo_urls'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'tags'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'status'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + # validator = Petstore::EnumTest::EnumAttributeValidator.new("String", ["available", "pending", "sold"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/tag_spec.cr b/samples/client/petstore/crystal/spec/models/tag_spec.cr new file mode 100644 index 00000000000..f79e12657fc --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/tag_spec.cr @@ -0,0 +1,38 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::Tag +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Tag do + + describe "test an instance of Tag" do + it "should create an instance of Tag" do + #instance = Petstore::Tag.new + #expect(instance).to be_instance_of(Petstore::Tag) + end + end + describe "test attribute 'id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'name'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/user_spec.cr b/samples/client/petstore/crystal/spec/models/user_spec.cr new file mode 100644 index 00000000000..6e52fc2c5bd --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/user_spec.cr @@ -0,0 +1,74 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.0.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::User +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::User do + + describe "test an instance of User" do + it "should create an instance of User" do + #instance = Petstore::User.new + #expect(instance).to be_instance_of(Petstore::User) + end + end + describe "test attribute 'id'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'username'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'first_name'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'last_name'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'email'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'password'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'phone'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'user_status'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/spec_helper.cr b/samples/client/petstore/crystal/spec/spec_helper.cr new file mode 100644 index 00000000000..cf4e0720754 --- /dev/null +++ b/samples/client/petstore/crystal/spec/spec_helper.cr @@ -0,0 +1,14 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +# load modules +require "spec" +require "json" +require "../src/petstore" \ No newline at end of file diff --git a/samples/client/petstore/crystal/src/petstore.cr b/samples/client/petstore/crystal/src/petstore.cr new file mode 100644 index 00000000000..63875570707 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore.cr @@ -0,0 +1,35 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +# Dependencies +require "crest" +require "log" + +module Petstore + Log = ::Log.for("Petstore") # => Log for Petstore source + + VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + + # Customize default settings for the SDK using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end +end + +require "./petstore/**" diff --git a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr new file mode 100644 index 00000000000..3bd722bfa01 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr @@ -0,0 +1,493 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "uri" + +module Petstore + class PetApi + property api_client : ApiClient + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Add a new pet to the store + # @param pet [Pet] Pet object that needs to be added to the store + # @return [Pet] + def add_pet(pet : Pet) + data, _status_code, _headers = add_pet_with_http_info(pet) + data + end + + # Add a new pet to the store + # @param pet [Pet] Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def add_pet_with_http_info(pet : Pet) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.add_pet ..."} + end + # verify the required parameter "pet" is set + if @api_client.config.client_side_validation && pet.nil? + raise ArgumentError.new("Missing the required parameter 'pet' when calling PetApi.add_pet") + end + # resource path + local_var_path = "/pet" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = pet.to_json + + # return_type + return_type = "Pet" + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"PetApi.add_pet", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Pet.from_json(data), status_code, headers + end + + # Deletes a pet + # @param pet_id [Int64] Pet id to delete + # @return [nil] + def delete_pet(pet_id : Int64, api_key : String?) + delete_pet_with_http_info(pet_id, api_key) + nil + end + + # Deletes a pet + # @param pet_id [Int64] Pet id to delete + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_pet_with_http_info(pet_id : Int64, api_key : String?) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.delete_pet ..."} + end + # verify the required parameter "pet_id" is set + if @api_client.config.client_side_validation && pet_id.nil? + raise ArgumentError.new("Missing the required parameter 'pet_id' when calling PetApi.delete_pet") + end + # resource path + local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + header_params["api_key"] = api_key + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:DELETE, + local_var_path, + :"PetApi.delete_pet", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status [Array(String)] Status values that need to be considered for filter + # @return [Array(Pet)] + def find_pets_by_status(status : Array(String)) + data, _status_code, _headers = find_pets_by_status_with_http_info(status) + data + end + + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status [Array(String)] Status values that need to be considered for filter + # @return [Array<(Array(Pet), Integer, Hash)>] Array(Pet) data, response status code and response headers + def find_pets_by_status_with_http_info(status : Array(String)) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.find_pets_by_status ..."} + end + # verify the required parameter "status" is set + if @api_client.config.client_side_validation && status.nil? + raise ArgumentError.new("Missing the required parameter 'status' when calling PetApi.find_pets_by_status") + end + # resource path + local_var_path = "/pet/findByStatus" + + # query parameters + query_params = Hash(Symbol, String).new + query_params[:"status"] = @api_client.build_collection_param(status, :csv) + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "Array(Pet)" + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"PetApi.find_pets_by_status", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Array(Pet).from_json(data), status_code, headers + end + + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags [Array(String)] Tags to filter by + # @return [Array(Pet)] + def find_pets_by_tags(tags : Array(String)) + data, _status_code, _headers = find_pets_by_tags_with_http_info(tags) + data + end + + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags [Array(String)] Tags to filter by + # @return [Array<(Array(Pet), Integer, Hash)>] Array(Pet) data, response status code and response headers + def find_pets_by_tags_with_http_info(tags : Array(String)) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.find_pets_by_tags ..."} + end + # verify the required parameter "tags" is set + if @api_client.config.client_side_validation && tags.nil? + raise ArgumentError.new("Missing the required parameter 'tags' when calling PetApi.find_pets_by_tags") + end + # resource path + local_var_path = "/pet/findByTags" + + # query parameters + query_params = Hash(Symbol, String).new + query_params[:"tags"] = @api_client.build_collection_param(tags, :csv) + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "Array(Pet)" + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"PetApi.find_pets_by_tags", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Array(Pet).from_json(data), status_code, headers + end + + # Find pet by ID + # Returns a single pet + # @param pet_id [Int64] ID of pet to return + # @return [Pet] + def get_pet_by_id(pet_id : Int64) + data, _status_code, _headers = get_pet_by_id_with_http_info(pet_id) + data + end + + # Find pet by ID + # Returns a single pet + # @param pet_id [Int64] ID of pet to return + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def get_pet_by_id_with_http_info(pet_id : Int64) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.get_pet_by_id ..."} + end + # verify the required parameter "pet_id" is set + if @api_client.config.client_side_validation && pet_id.nil? + raise ArgumentError.new("Missing the required parameter 'pet_id' when calling PetApi.get_pet_by_id") + end + # resource path + local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "Pet" + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"PetApi.get_pet_by_id", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Pet.from_json(data), status_code, headers + end + + # Update an existing pet + # @param pet [Pet] Pet object that needs to be added to the store + # @return [Pet] + def update_pet(pet : Pet) + data, _status_code, _headers = update_pet_with_http_info(pet) + data + end + + # Update an existing pet + # @param pet [Pet] Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def update_pet_with_http_info(pet : Pet) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.update_pet ..."} + end + # verify the required parameter "pet" is set + if @api_client.config.client_side_validation && pet.nil? + raise ArgumentError.new("Missing the required parameter 'pet' when calling PetApi.update_pet") + end + # resource path + local_var_path = "/pet" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = pet.to_json + + # return_type + return_type = "Pet" + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:PUT, + local_var_path, + :"PetApi.update_pet", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Pet.from_json(data), status_code, headers + end + + # Updates a pet in the store with form data + # @param pet_id [Int64] ID of pet that needs to be updated + # @return [nil] + def update_pet_with_form(pet_id : Int64, name : String?, status : String?) + update_pet_with_form_with_http_info(pet_id, name, status) + nil + end + + # Updates a pet in the store with form data + # @param pet_id [Int64] ID of pet that needs to be updated + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def update_pet_with_form_with_http_info(pet_id : Int64, name : String?, status : String?) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.update_pet_with_form ..."} + end + # verify the required parameter "pet_id" is set + if @api_client.config.client_side_validation && pet_id.nil? + raise ArgumentError.new("Missing the required parameter 'pet_id' when calling PetApi.update_pet_with_form") + end + # resource path + local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/x-www-form-urlencoded"]) + + # form parameters + form_params = Hash(Symbol, String).new + form_params[:"name"] = name + form_params[:"status"] = status + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"PetApi.update_pet_with_form", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # uploads an image + # @param pet_id [Int64] ID of pet to update + # @return [ApiResponse] + def upload_file(pet_id : Int64, additional_metadata : String?, file : File?) + data, _status_code, _headers = upload_file_with_http_info(pet_id, additional_metadata, file) + data + end + + # uploads an image + # @param pet_id [Int64] ID of pet to update + # @return [Array<(ApiResponse, Integer, Hash)>] ApiResponse data, response status code and response headers + def upload_file_with_http_info(pet_id : Int64, additional_metadata : String?, file : File?) + if @api_client.config.debugging + Log.debug {"Calling API: PetApi.upload_file ..."} + end + # verify the required parameter "pet_id" is set + if @api_client.config.client_side_validation && pet_id.nil? + raise ArgumentError.new("Missing the required parameter 'pet_id' when calling PetApi.upload_file") + end + # resource path + local_var_path = "/pet/{petId}/uploadImage".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/json"]) + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["multipart/form-data"]) + + # form parameters + form_params = Hash(Symbol, String).new + form_params[:"additionalMetadata"] = additional_metadata + form_params[:"file"] = file + + # http body (model) + post_body = nil + + # return_type + return_type = "ApiResponse" + + # auth_names + auth_names = ["petstore_auth"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"PetApi.upload_file", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return ApiResponse.from_json(data), status_code, headers + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/api/store_api.cr b/samples/client/petstore/crystal/src/petstore/api/store_api.cr new file mode 100644 index 00000000000..4b4311073a5 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api/store_api.cr @@ -0,0 +1,256 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "uri" + +module Petstore + class StoreApi + property api_client : ApiClient + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id [String] ID of the order that needs to be deleted + # @return [nil] + def delete_order(order_id : String) + delete_order_with_http_info(order_id) + nil + end + + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id [String] ID of the order that needs to be deleted + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_order_with_http_info(order_id : String) + if @api_client.config.debugging + Log.debug {"Calling API: StoreApi.delete_order ..."} + end + # verify the required parameter "order_id" is set + if @api_client.config.client_side_validation && order_id.nil? + raise ArgumentError.new("Missing the required parameter 'order_id' when calling StoreApi.delete_order") + end + # resource path + local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:DELETE, + local_var_path, + :"StoreApi.delete_order", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: StoreApi#delete_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @return [Hash(String, Int32)] + def get_inventory() + data, _status_code, _headers = get_inventory_with_http_info() + data + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @return [Array<(Hash(String, Int32), Integer, Hash)>] Hash(String, Int32) data, response status code and response headers + def get_inventory_with_http_info() + if @api_client.config.debugging + Log.debug {"Calling API: StoreApi.get_inventory ..."} + end + # resource path + local_var_path = "/store/inventory" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "Hash(String, Int32)" + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"StoreApi.get_inventory", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Hash(String, Int32).from_json(data), status_code, headers + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id [Int64] ID of pet that needs to be fetched + # @return [Order] + def get_order_by_id(order_id : Int64) + data, _status_code, _headers = get_order_by_id_with_http_info(order_id) + data + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id [Int64] ID of pet that needs to be fetched + # @return [Array<(Order, Integer, Hash)>] Order data, response status code and response headers + def get_order_by_id_with_http_info(order_id : Int64) + if @api_client.config.debugging + Log.debug {"Calling API: StoreApi.get_order_by_id ..."} + end + # verify the required parameter "order_id" is set + if @api_client.config.client_side_validation && order_id.nil? + raise ArgumentError.new("Missing the required parameter 'order_id' when calling StoreApi.get_order_by_id") + end + if @api_client.config.client_side_validation && order_id > 5 + raise ArgumentError.new("invalid value for \"order_id\" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.") + end + + if @api_client.config.client_side_validation && order_id < 1 + raise ArgumentError.new("invalid value for \"order_id\" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.") + end + + # resource path + local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "Order" + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"StoreApi.get_order_by_id", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Order.from_json(data), status_code, headers + end + + # Place an order for a pet + # @param order [Order] order placed for purchasing the pet + # @return [Order] + def place_order(order : Order) + data, _status_code, _headers = place_order_with_http_info(order) + data + end + + # Place an order for a pet + # @param order [Order] order placed for purchasing the pet + # @return [Array<(Order, Integer, Hash)>] Order data, response status code and response headers + def place_order_with_http_info(order : Order) + if @api_client.config.debugging + Log.debug {"Calling API: StoreApi.place_order ..."} + end + # verify the required parameter "order" is set + if @api_client.config.client_side_validation && order.nil? + raise ArgumentError.new("Missing the required parameter 'order' when calling StoreApi.place_order") + end + # resource path + local_var_path = "/store/order" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = order.to_json + + # return_type + return_type = "Order" + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"StoreApi.place_order", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return Order.from_json(data), status_code, headers + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/api/user_api.cr b/samples/client/petstore/crystal/src/petstore/api/user_api.cr new file mode 100644 index 00000000000..eefeeea2ab0 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api/user_api.cr @@ -0,0 +1,491 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "uri" + +module Petstore + class UserApi + property api_client : ApiClient + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Create user + # This can only be done by the logged in user. + # @param user [User] Created user object + # @return [nil] + def create_user(user : User) + create_user_with_http_info(user) + nil + end + + # Create user + # This can only be done by the logged in user. + # @param user [User] Created user object + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_user_with_http_info(user : User) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.create_user ..."} + end + # verify the required parameter "user" is set + if @api_client.config.client_side_validation && user.nil? + raise ArgumentError.new("Missing the required parameter 'user' when calling UserApi.create_user") + end + # resource path + local_var_path = "/user" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = user.to_json + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"UserApi.create_user", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Creates list of users with given input array + # @param user [Array(User)] List of user object + # @return [nil] + def create_users_with_array_input(user : Array(User)) + create_users_with_array_input_with_http_info(user) + nil + end + + # Creates list of users with given input array + # @param user [Array(User)] List of user object + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_users_with_array_input_with_http_info(user : Array(User)) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.create_users_with_array_input ..."} + end + # verify the required parameter "user" is set + if @api_client.config.client_side_validation && user.nil? + raise ArgumentError.new("Missing the required parameter 'user' when calling UserApi.create_users_with_array_input") + end + # resource path + local_var_path = "/user/createWithArray" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = user.to_json + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"UserApi.create_users_with_array_input", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Creates list of users with given input array + # @param user [Array(User)] List of user object + # @return [nil] + def create_users_with_list_input(user : Array(User)) + create_users_with_list_input_with_http_info(user) + nil + end + + # Creates list of users with given input array + # @param user [Array(User)] List of user object + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_users_with_list_input_with_http_info(user : Array(User)) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.create_users_with_list_input ..."} + end + # verify the required parameter "user" is set + if @api_client.config.client_side_validation && user.nil? + raise ArgumentError.new("Missing the required parameter 'user' when calling UserApi.create_users_with_list_input") + end + # resource path + local_var_path = "/user/createWithList" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = user.to_json + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:POST, + local_var_path, + :"UserApi.create_users_with_list_input", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Delete user + # This can only be done by the logged in user. + # @param username [String] The name that needs to be deleted + # @return [nil] + def delete_user(username : String) + delete_user_with_http_info(username) + nil + end + + # Delete user + # This can only be done by the logged in user. + # @param username [String] The name that needs to be deleted + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_user_with_http_info(username : String) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.delete_user ..."} + end + # verify the required parameter "username" is set + if @api_client.config.client_side_validation && username.nil? + raise ArgumentError.new("Missing the required parameter 'username' when calling UserApi.delete_user") + end + # resource path + local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:DELETE, + local_var_path, + :"UserApi.delete_user", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Get user by user name + # @param username [String] The name that needs to be fetched. Use user1 for testing. + # @return [User] + def get_user_by_name(username : String) + data, _status_code, _headers = get_user_by_name_with_http_info(username) + data + end + + # Get user by user name + # @param username [String] The name that needs to be fetched. Use user1 for testing. + # @return [Array<(User, Integer, Hash)>] User data, response status code and response headers + def get_user_by_name_with_http_info(username : String) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.get_user_by_name ..."} + end + # verify the required parameter "username" is set + if @api_client.config.client_side_validation && username.nil? + raise ArgumentError.new("Missing the required parameter 'username' when calling UserApi.get_user_by_name") + end + # resource path + local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "User" + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"UserApi.get_user_by_name", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return User.from_json(data), status_code, headers + end + + # Logs user into the system + # @param username [String] The user name for login + # @param password [String] The password for login in clear text + # @return [String] + def login_user(username : String, password : String) + data, _status_code, _headers = login_user_with_http_info(username, password) + data + end + + # Logs user into the system + # @param username [String] The user name for login + # @param password [String] The password for login in clear text + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def login_user_with_http_info(username : String, password : String) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.login_user ..."} + end + # verify the required parameter "username" is set + if @api_client.config.client_side_validation && username.nil? + raise ArgumentError.new("Missing the required parameter 'username' when calling UserApi.login_user") + end + pattern = Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/) + if @api_client.config.client_side_validation && username !~ pattern + raise ArgumentError.new("invalid value for \"username\" when calling UserApi.login_user, must conform to the pattern #{pattern}.") + end + + # verify the required parameter "password" is set + if @api_client.config.client_side_validation && password.nil? + raise ArgumentError.new("Missing the required parameter 'password' when calling UserApi.login_user") + end + # resource path + local_var_path = "/user/login" + + # query parameters + query_params = Hash(Symbol, String).new + query_params[:"username"] = username + query_params[:"password"] = password + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Accept" (if needed) + header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = "String" + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"UserApi.login_user", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return String.from_json(data), status_code, headers + end + + # Logs out current logged in user session + # @return [nil] + def logout_user() + logout_user_with_http_info() + nil + end + + # Logs out current logged in user session + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def logout_user_with_http_info() + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.logout_user ..."} + end + # resource path + local_var_path = "/user/logout" + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"UserApi.logout_user", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + + # Updated user + # This can only be done by the logged in user. + # @param username [String] name that need to be deleted + # @param user [User] Updated user object + # @return [nil] + def update_user(username : String, user : User) + update_user_with_http_info(username, user) + nil + end + + # Updated user + # This can only be done by the logged in user. + # @param username [String] name that need to be deleted + # @param user [User] Updated user object + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def update_user_with_http_info(username : String, user : User) + if @api_client.config.debugging + Log.debug {"Calling API: UserApi.update_user ..."} + end + # verify the required parameter "username" is set + if @api_client.config.client_side_validation && username.nil? + raise ArgumentError.new("Missing the required parameter 'username' when calling UserApi.update_user") + end + # verify the required parameter "user" is set + if @api_client.config.client_side_validation && user.nil? + raise ArgumentError.new("Missing the required parameter 'user' when calling UserApi.update_user") + end + # resource path + local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) + + # query parameters + query_params = Hash(Symbol, String).new + + # header parameters + header_params = Hash(String, String).new + # HTTP header "Content-Type" + header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) + + # form parameters + form_params = Hash(Symbol, String).new + + # http body (model) + post_body = user.to_json + + # return_type + return_type = nil + + # auth_names + auth_names = ["api_key"] + + data, status_code, headers = @api_client.call_api(:PUT, + local_var_path, + :"UserApi.update_user", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/api_client.cr b/samples/client/petstore/crystal/src/petstore/api_client.cr new file mode 100644 index 00000000000..b768948f758 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api_client.cr @@ -0,0 +1,410 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "json" +require "time" + +module Petstore + class ApiClient + # The Configuration object holding settings to be used in the API client. + property config : Configuration + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + property default_headers : Hash(String, String) + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(@config = Configuration.default) + @user_agent = "OpenAPI-Generator/#{VERSION}/crystal" + @default_headers = { + "User-Agent" => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + + # handle file downloading - return the File instance processed in request callbacks + # note that response body is empty when the file is written in chunks in request on_body callback + if return_type == "File" + content_disposition = response.headers["Content-Disposition"].to_s + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition.match(/filename=[""]?([^""\s]+)[""]?/i).try &.[0] + prefix = sanitize_filename(filename) + else + prefix = "download-" + end + if !prefix.nil? && prefix.ends_with?("-") + prefix = prefix + "-" + end + encoding = response.headers["Content-Encoding"].to_s + + # TODO add file support + raise ApiError.new(code: 0, message: "File response not yet supported in the client.") if return_type + return nil + + #@tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + #@tempfile.write(@stream.join.force_encoding(encoding)) + #@tempfile.close + #Log.info { "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\ + # "with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\ + # "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + # "explicitly with `tempfile.delete`" } + #return @tempfile + end + + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body if return_type == "String" + + # ensuring a default content type + content_type = response.headers["Content-Type"] || "application/json" + + raise ApiError.new(code: 0, message: "Content-Type is not supported: #{content_type}") unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]")[0] + rescue e : Exception + if %w(String Date Time).includes?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when "String" + data.to_s + when "Integer" + data.to_s.to_i + when "Float" + data.to_s.to_f + when "Boolean" + data == true + when "Time" + # parse date time (expecting ISO 8601 format) + Time.parse! data.to_s, "%Y-%m-%dT%H:%M:%S%Z" + when "Date" + # parse date (expecting ISO 8601 format) + Time.parse! data.to_s, "%Y-%m-%d" + when "Object" + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + ({} of Symbol => String).tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + if filename.nil? + return nil + else + filename.gsub(/.*[\/\\]/, "") + end + end + + def build_request_url(path : String, operation : Symbol) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, "/") + @config.base_url(operation) + path + end + + # Update hearder and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array{auth_names}.each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when "header" then header_params[auth_setting[:key]] = auth_setting[:value] + when "query" then query_params[auth_setting[:key]] = auth_setting[:value] + else raise ArgumentError.new("Authentication token must be in `query` of `header`") + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers["User-Agent"] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) : String + #return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + if json_accept.nil? + accepts.join(",") + else + json_accept + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # use application/json by default + return "application/json" if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(",") + when :ssv + param.join(" ") + when :tsv + param.join("\t") + when :pipes + param.join("|") + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + #ssl_options = { + # :ca_file => @config.ssl_ca_file, + # :verify => @config.ssl_verify, + # :verify_mode => @config.ssl_verify_mode, + # :client_cert => @config.ssl_client_cert, + # :client_key => @config.ssl_client_key + #} + + #connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn| + # conn.basic_auth(config.username, config.password) + # if opts[:header_params]["Content-Type"] == "multipart/form-data" + # conn.request :multipart + # conn.request :url_encoded + # end + # conn.adapter(Faraday.default_adapter) + #end + + if !post_body.nil? && !post_body.empty? + # use JSON string in the payload + form_or_body = post_body + else + # use HTTP forms in the payload + # TDOD use HTTP form encoding + form_or_body = form_params + end + + request = Crest::Request.new(http_method, + build_request_url(path, operation), + params: query_params, + headers: header_params, + #cookies: cookie_params, # TODO add cookies support + form: form_or_body, + logging: @config.debugging, + handle_errors: false + ) + + response = request.execute + + if @config.debugging + Log.debug {"HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"} + end + + if !response.success? + if response.status == 0 + # Errors from libcurl will be made visible here + raise ApiError.new(code: 0, + message: response.body) + else + raise ApiError.new(code: response.status_code, + response_headers: response.headers, + message: response.body) + end + end + + return response.body, response.status_code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, request, opts = {} of Symbol => String) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String) + query_params = opts[:query_params] || {} of Symbol => String + form_params = opts[:form_params] || {} of Symbol => String + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :verbose => @config.debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update body: req_body + if @config.debugging + Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"} + end + end + request.headers = header_params + request.body = req_body + request.url url + request.params = query_params + download_file(request) if opts[:return_type] == "File" + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params["Content-Type"] == "application/x-www-form-urlencoded" + data = URI.encode_www_form(form_params) + elsif header_params["Content-Type"] == "multipart/form-data" + data = {} of Symbol => String + form_params.each do |key, value| + case value + when ::File, ::Tempfile + # TODO hardcode to application/octet-stream, need better way to detect content type + data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path) + when ::Array, nil + # let Faraday handle Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # TODO fix streaming response + #def download_file(request) + # @stream = [] + + # # handle streaming Responses + # request.options.on_data = Proc.new do |chunk, overall_received_bytes| + # @stream << chunk + # end + #end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/api_error.cr b/samples/client/petstore/crystal/src/petstore/api_error.cr new file mode 100644 index 00000000000..8c7df2fc2a8 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api_error.cr @@ -0,0 +1,41 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +module Petstore + class ApiError < Exception + getter code : Int32? + getter response_headers : Hash(String, Array(String) | String)? + + # Usage examples: + # ApiError.new + # ApiError.new(message: "message") + # ApiError.new(code: 500, response_headers: {}, message: "") + # ApiError.new(code: 404, message: "Not Found") + def initialize(@code , @message, @response_headers) + end + + def initialize(@code , @message) + end + + # Override to_s to display a friendly error message + def to_s + msg = "" + msg = msg + "\nHTTP status code: #{code}" if @code + msg = msg + "\nResponse headers: #{response_headers}" if @response_headers + if @message.nil? || @message.empty? + msg = msg + "\nError message: the server returns an error but the HTTP respone body is empty." + else + msg = msg + "\nResponse body: #{@message}" + end + + msg + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/configuration.cr b/samples/client/petstore/crystal/src/petstore/configuration.cr new file mode 100644 index 00000000000..380963045b2 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/configuration.cr @@ -0,0 +1,271 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "log" + +module Petstore + class Configuration + # Defines url scheme + property scheme : String + + # Defines url host + property host : String + + # Defines url base path + property base_path : String + + # Define server configuration index + property server_index : Int32 + + # Define server operation configuration index + property server_operation_index : Hash(Symbol, String) + + # Default server variables + property server_variables : Hash(Symbol, String) + + # Default server operation variables + property server_operation_variables : Hash(Symbol, String) + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key[:"api_key"] = "xxx" + property api_key : Hash(Symbol, String) + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix[:"api_key"] = "Token" + property api_key_prefix : Hash(Symbol, String) + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + property username : String? + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + property password : String? + + # Defines the access token (Bearer) used with OAuth2. + property access_token : String? + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + property debugging : Bool + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + property temp_folder_path : String? + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + property timeout : Int32 + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + property client_side_validation : Bool + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + #TODO attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + # TODO attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + # TODO attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + # TODO attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + # TODO attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to Nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + #property params_encoding : String? + + def initialize + @scheme = "http" + @host = "petstore.swagger.io" + @base_path = "/v2" + @server_index = 0 + @server_operation_index = {} of Symbol => String + @server_variables = {} of Symbol => String + @server_operation_variables = {} of Symbol => String + @api_key = {} of Symbol => String + @api_key_prefix = {} of Symbol => String + @timeout = 0 + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + #@params_encoding = nil + #@cert_file = nil + #@key_file = nil + @debugging = false + @username = nil + @password = nil + @access_token = nil + @temp_folder_path = nil + + # TODO revise below to support block + #yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, "") + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, "").split("/").first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, "/") + @base_path = "" if @base_path == "/" + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = Nil) + # TODO revise below to support operation-level server setting + #index = server_operation_index.fetch(operation, server_index) + return "#{scheme}://#{[host, base_path].join("/").gsub(/\/+/, "/")}".sub(/\/+\z/, "") #if index == Nil + + #server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + "Basic " + ["#{username}:#{password}"].pack("m").delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + Hash{ "api_key" => { + type: "api_key", + in: "header", + key: "api_key", + value: api_key_with_prefix("api_key") + }, + "petstore_auth" => + { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + } + ] + end + + def operation_server_settings + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {} of Symbol => String, servers = Nil) + servers = server_settings if servers == Nil + + # check array index out of bound + if (index < 0 || index >= servers.size) + raise ArgumentError.new("Invalid index #{index} when selecting the server. Must be less than #{servers.size}") + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + raise ArgumentError.new("The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}.") + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr new file mode 100644 index 00000000000..f6e71542f7e --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -0,0 +1,188 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # Describes the result of uploading an image resource + class ApiResponse include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: code, type: Int32)] + property code : Int32 + + + @[JSON::Field(key: type, type: String)] + property _type : String + + + @[JSON::Field(key: message, type: String)] + property message : String + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@code : Int32 | Nil, @_type : String | Nil, @message : String | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + code == o.code && + _type == o._type && + message == o.message + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [code, _type, message].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr new file mode 100644 index 00000000000..0fab536acb3 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -0,0 +1,200 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # A category for a pet + class Category include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] + property id : Int64 + + + @[JSON::Field(key: name, type: String)] + property name : String + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@id : Int64 | Nil, @name : String | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + pattern = Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/) + if !@name.nil? && @name !~ pattern + invalid_properties.push("invalid value for \"name\", must conform to the pattern #{pattern}.") + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if !@name.nil? && @name !~ Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/) + true + end + + # Custom attribute writer method with validation + # @param [Object] name Value to be assigned + def name=(name) + pattern = Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/) + if !name.nil? && name !~ pattern + raise ArgumentError.new("invalid value for \"name\", must conform to the pattern #{pattern}.") + end + + @name = name + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr new file mode 100644 index 00000000000..634d33fdae7 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -0,0 +1,239 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # An order for a pets from the pet store + class Order include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] + property id : Int64 + + + @[JSON::Field(key: petId, type: Int64)] + property pet_id : Int64 + + + @[JSON::Field(key: quantity, type: Int32)] + property quantity : Int32 + + + @[JSON::Field(key: shipDate, type: Time)] + property ship_date : Time + + + # Order Status + @[JSON::Field(key: status, type: String)] + property status : String + + + @[JSON::Field(key: complete, type: Bool)] + property complete : Bool + + class EnumAttributeValidator + getter datatype : String + getter allowable_values : Array(String) + + def initialize(datatype, allowable_values) + @datatype = datatype + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@id : Int64 | Nil, @pet_id : Int64 | Nil, @quantity : Int32 | Nil, @ship_date : Time | Nil, @status : String | Nil, @complete : Bool | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + status_validator = EnumAttributeValidator.new("String", ["placed", "approved", "delivered"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new("String", ["placed", "approved", "delivered"]) + unless validator.valid?(status) + raise ArgumentError.new("invalid value for \"status\", must be one of #{validator.allowable_values}.") + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + pet_id == o.pet_id && + quantity == o.quantity && + ship_date == o.ship_date && + status == o.status && + complete == o.complete + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, pet_id, quantity, ship_date, status, complete].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr new file mode 100644 index 00000000000..d4431c6aa1e --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -0,0 +1,249 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # A pet for sale in the pet store + class Pet include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] + property id : Int64 + + + @[JSON::Field(key: category, type: Category)] + property category : Category + + + @[JSON::Field(key: name, type: String)] + property name : String + + + @[JSON::Field(key: photoUrls, type: Array(String))] + property photo_urls : Array(String) + + + @[JSON::Field(key: tags, type: Array(Tag))] + property tags : Array(Tag) + + + # pet status in the store + @[JSON::Field(key: status, type: String)] + property status : String + + class EnumAttributeValidator + getter datatype : String + getter allowable_values : Array(String) + + def initialize(datatype, allowable_values) + @datatype = datatype + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@id : Int64 | Nil, @category : Category | Nil, @name : String, @photo_urls : Array(String), @tags : Array(Tag) | Nil, @status : String | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @name.nil? + invalid_properties.push("invalid value for \"name\", name cannot be nil.") + end + + if @photo_urls.nil? + invalid_properties.push("invalid value for \"photo_urls\", photo_urls cannot be nil.") + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @name.nil? + return false if @photo_urls.nil? + status_validator = EnumAttributeValidator.new("String", ["available", "pending", "sold"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new("String", ["available", "pending", "sold"]) + unless validator.valid?(status) + raise ArgumentError.new("invalid value for \"status\", must be one of #{validator.allowable_values}.") + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + category == o.category && + name == o.name && + photo_urls == o.photo_urls && + tags == o.tags && + status == o.status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, category, name, photo_urls, tags, status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr new file mode 100644 index 00000000000..fa2968a9035 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -0,0 +1,183 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # A tag for a pet + class Tag include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] + property id : Int64 + + + @[JSON::Field(key: name, type: String)] + property name : String + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@id : Int64 | Nil, @name : String | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr new file mode 100644 index 00000000000..d3922e82394 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -0,0 +1,214 @@ +# #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 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 5.1.0-SNAPSHOT +# + +require "time" + +module Petstore + # A User who is purchasing from the pet store + class User include JSON::Serializable + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] + property id : Int64 + + + @[JSON::Field(key: username, type: String)] + property username : String + + + @[JSON::Field(key: firstName, type: String)] + property first_name : String + + + @[JSON::Field(key: lastName, type: String)] + property last_name : String + + + @[JSON::Field(key: email, type: String)] + property email : String + + + @[JSON::Field(key: password, type: String)] + property password : String + + + @[JSON::Field(key: phone, type: String)] + property phone : String + + + # User Status + @[JSON::Field(key: userStatus, type: Int32)] + property user_status : Int32 + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@id : Int64 | Nil, @username : String | Nil, @first_name : String | Nil, @last_name : String | Nil, @email : String | Nil, @password : String | Nil, @phone : String | Nil, @user_status : Int32 | Nil) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + username == o.username && + first_name == o.first_name && + last_name == o.last_name && + email == o.email && + password == o.password && + phone == o.phone && + user_status == o.user_status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, username, first_name, last_name, email, password, phone, user_status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml b/samples/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml index 655cb67bd88..a611887d3ac 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml +++ b/samples/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml @@ -1 +1,9 @@ -analyzer: \ No newline at end of file +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api.dart index fb9635ab642..2422d33a0f3 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library openapi.api; import 'package:dio/dio.dart'; diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart index c975d10e631..dc84d61c998 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -29,33 +36,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(body); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, body); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -87,27 +95,27 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; headerParams[r'api_key'] = apiKey; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -138,27 +146,27 @@ class PetApi { }) async { final String _path = '/pet/findByStatus'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'status'] = status; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -175,7 +183,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -203,27 +216,27 @@ class PetApi { }) async { final String _path = '/pet/findByTags'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'tags'] = tags; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -240,7 +253,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -268,26 +286,26 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -304,8 +322,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Pet); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Pet) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -333,33 +354,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(body); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, body); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -392,33 +414,33 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['name'] = parameterToString(_serializers, name); formData['status'] = parameterToString(_serializers, status); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -451,20 +473,20 @@ class PetApi { }) async { final String _path = '/pet/{petId}/uploadImage'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'multipart/form-data', ]; - final Map formData = {}; + final formData = {}; if (additionalMetadata != null) { formData[r'additionalMetadata'] = parameterToString(_serializers, additionalMetadata); } @@ -473,15 +495,15 @@ class PetApi { } bodyData = FormData.fromMap(formData); - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -496,8 +518,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ApiResponse); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ApiResponse) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart index eb62c2dc17f..ed20fd6fce5 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,26 +33,26 @@ class StoreApi { }) async { final String _path = '/store/order/{orderId}'.replaceAll('{' r'orderId' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -70,26 +77,26 @@ class StoreApi { }) async { final String _path = '/store/inventory'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -108,7 +115,12 @@ class StoreApi { ).then((response) { const collectionType = BuiltMap; const type = FullType(collectionType, [FullType(String), FullType(int)]); - final BuiltMap data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltMap; return Response>( data: data, @@ -136,26 +148,26 @@ class StoreApi { }) async { final String _path = '/store/order/{orderId}'.replaceAll('{' r'orderId' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -165,8 +177,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -194,30 +209,31 @@ class StoreApi { }) async { final String _path = '/store/order'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - final serializedBody = _serializers.serialize(body); + final bodySerializer = _serializers.serializerForType(Order) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, body); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -227,8 +243,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart index 9183e1f5a76..fc504efe821 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,30 +33,31 @@ class UserApi { }) async { final String _path = '/user'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - final serializedBody = _serializers.serialize(body); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, body); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -75,31 +83,31 @@ class UserApi { }) async { final String _path = '/user/createWithArray'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; const type = FullType(BuiltList, [FullType(User)]); final serializedBody = _serializers.serialize(body, specifiedType: type); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -125,31 +133,31 @@ class UserApi { }) async { final String _path = '/user/createWithList'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; const type = FullType(BuiltList, [FullType(User)]); final serializedBody = _serializers.serialize(body, specifiedType: type); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -175,26 +183,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -220,26 +228,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -249,8 +257,11 @@ class UserApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(User); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(User) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -279,28 +290,28 @@ class UserApi { }) async { final String _path = '/user/login'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'username'] = username; queryParams[r'password'] = password; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -337,26 +348,26 @@ class UserApi { }) async { final String _path = '/user/logout'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -383,30 +394,31 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - final serializedBody = _serializers.serialize(body); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, body); final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart index e99530f6c39..361fab65af5 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:convert'; import 'package:built_value/serializer.dart'; diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart index 6cde089a9a1..76c1fc890c8 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class ApiKeyAuthInterceptor extends AuthInterceptor { Map apiKeys = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "apiKey"); - for (var info in authInfo) { - final authName = info["name"]; - final authKeyName = info["keyName"]; - final authWhere = info["where"]; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; final apiKey = apiKeys[authName]; if (apiKey != null) { if (authWhere == 'query') { diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart index 703127c762b..1cca446ee78 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart @@ -1,4 +1,9 @@ -import 'dart:async'; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import import 'package:dio/dio.dart'; @@ -8,11 +13,11 @@ abstract class AuthInterceptor extends Interceptor { * Can return null if type is not present on auth data or if route doesn't need authentication */ List> getAuthInfo(RequestOptions route, String type) { - if (route.extra.containsKey("secure")) { - final auth = route.extra["secure"]; - List> results = []; - for (var info in auth) { - if(info["type"] == type) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + final results = >[]; + for (final info in auth) { + if (info['type'] == type) { results.add(info); } } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart index 14334a2d288..1f9a2e281f5 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:openapi/auth/auth.dart'; @@ -14,13 +21,13 @@ class BasicAuthInterceptor extends AuthInterceptor { Map authInfo = {}; @override - Future onRequest(RequestOptions options) { + Future onRequest(RequestOptions options) { final metadataAuthInfo = getAuthInfo(options, 'basic'); - for (var info in metadataAuthInfo) { - final authName = info['name']; + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; final basicAuthInfo = authInfo[authName]; - if(basicAuthInfo != null) { - String basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); + if (basicAuthInfo != null) { + final basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); options.headers['Authorization'] = basicAuth; break; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart index 3fb06b580b9..481447bffdf 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class OAuthInterceptor extends AuthInterceptor { Map tokens = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "oauth"); - for (var info in authInfo) { - final token = tokens[info["name"]]; - if(token != null) { - options.headers["Authorization"] = "Bearer ${token}"; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'oauth'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; break; } } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart index 137b6de21ab..c5bc1e59646 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -22,7 +29,7 @@ abstract class ApiResponse implements Built { static void _initializeBuilder(ApiResponseBuilder b) => b; - factory ApiResponse([updates(ApiResponseBuilder b)]) = _$ApiResponse; + factory ApiResponse([void updates(ApiResponseBuilder b)]) = _$ApiResponse; static Serializer get serializer => _$apiResponseSerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart index c716072d768..ddd15d54a53 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Category implements Built { static void _initializeBuilder(CategoryBuilder b) => b; - factory Category([updates(CategoryBuilder b)]) = _$Category; + factory Category([void updates(CategoryBuilder b)]) = _$Category; static Serializer get serializer => _$categorySerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart index 517fba8eb73..f26c6213820 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -38,7 +45,7 @@ abstract class Order implements Built { static void _initializeBuilder(OrderBuilder b) => b ..complete = false; - factory Order([updates(OrderBuilder b)]) = _$Order; + factory Order([void updates(OrderBuilder b)]) = _$Order; static Serializer get serializer => _$orderSerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart index 1fb992db794..98757f5e7ce 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/tag.dart'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/model/category.dart'; @@ -39,7 +46,7 @@ abstract class Pet implements Built { static void _initializeBuilder(PetBuilder b) => b; - factory Pet([updates(PetBuilder b)]) = _$Pet; + factory Pet([void updates(PetBuilder b)]) = _$Pet; static Serializer get serializer => _$petSerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart index 8149a7d3498..528acd843e7 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Tag implements Built { static void _initializeBuilder(TagBuilder b) => b; - factory Tag([updates(TagBuilder b)]) = _$Tag; + factory Tag([void updates(TagBuilder b)]) = _$Tag; static Serializer get serializer => _$tagSerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart index 3fd4092d546..93259a43019 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -43,7 +50,7 @@ abstract class User implements Built { static void _initializeBuilder(UserBuilder b) => b; - factory User([updates(UserBuilder b)]) = _$User; + factory User([void updates(UserBuilder b)]) = _$User; static Serializer get serializer => _$userSerializer; } diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart b/samples/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart index 5db183b7438..b3c6cf6e1f1 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart +++ b/samples/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library serializers; import 'package:built_value/iso_8601_date_time_serializer.dart'; @@ -13,43 +20,31 @@ import 'package:openapi/model/pet.dart'; import 'package:openapi/model/tag.dart'; import 'package:openapi/model/user.dart'; - part 'serializers.g.dart'; @SerializersFor(const [ -ApiResponse, -Category, -Order, -Pet, -Tag, -User, - + ApiResponse, + Category, + Order, + Pet, + Tag, + User, ]) - -//allow all models to be serialized within a list Serializers serializers = (_$serializers.toBuilder() -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ApiResponse)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Category)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Order)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Pet)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Tag)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(User)]), -() => new ListBuilder()) - -..add(Iso8601DateTimeSerializer()) -).build(); + ..addBuilderFactory( + const FullType(BuiltList, [FullType(Pet)]), + () => ListBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltMap, [FullType(String), FullType(int)]), + () => MapBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), + ) + ..add(Iso8601DateTimeSerializer())) + .build(); Serializers standardSerializers = -(serializers.toBuilder() -..addPlugin(StandardJsonPlugin())).build(); + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/pom.xml b/samples/client/petstore/dart-dio/petstore_client_lib/pom.xml index 4f661ca5a8d..3b0a69b823f 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/pom.xml +++ b/samples/client/petstore/dart-dio/petstore_client_lib/pom.xml @@ -67,6 +67,22 @@ + + dartanalyzer + integration-test + + exec + + + dartanalyzer + + --fatal-infos + --options + analysis_options.yaml + . + + + pub-test integration-test diff --git a/samples/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml b/samples/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml index 20b190aa1d3..c7c5c5aec83 100644 --- a/samples/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml +++ b/samples/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml @@ -2,7 +2,7 @@ name: openapi version: 1.0.0 description: OpenAPI API client environment: - sdk: ">=2.3.0 <3.0.0" + sdk: ">=2.6.0 <3.0.0" dependencies: dio: ^3.0.9 built_value: ^7.1.0 diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index d8325401312..7399a873be4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -313,7 +313,7 @@ public class ApiClient extends JavaTimeFormatter { * * @param secrets Hash map from authentication name to its secret. */ - public ApiClient configureApiKeys(HashMap secrets) { + public ApiClient configureApiKeys(Map secrets) { for (Map.Entry authEntry : authentications.entrySet()) { Authentication auth = authEntry.getValue(); if (auth instanceof ApiKeyAuth) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java index 0a2f38a339c..3081ccf0871 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java @@ -476,6 +476,15 @@ public class ApiClient { return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); } + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -490,7 +499,7 @@ public class ApiClient { } for (String accept : accepts) { MediaType mediaType = MediaType.parseMediaType(accept); - if (isJsonMime(mediaType)) { + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { return Collections.singletonList(mediaType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java index acb991c6606..335a146e1d8 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java @@ -471,6 +471,15 @@ public class ApiClient { return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); } + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -485,7 +494,7 @@ public class ApiClient { } for (String accept : accepts) { MediaType mediaType = MediaType.parseMediaType(accept); - if (isJsonMime(mediaType)) { + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { return Collections.singletonList(mediaType); } } diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..e4f7f4eeae0 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/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-gson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..5d64a9add42 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(value)) + } + }.build() + } + mediaType == JsonMediaType -> Serializer.gson.toJson(content, T::class.java).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.gson.fromJson(bodyContent, T::class.java) + 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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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.gson.toJson(value, T::class.java).replace("\"", "") + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-gson/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/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-gson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..6120b081929 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,33 @@ +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 + +class ByteArrayAdapter : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: ByteArray?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(String(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): ByteArray? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return out.nextString().toByteArray() + } + } + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/DateAdapter.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/DateAdapter.kt new file mode 100644 index 00000000000..c5d330ac075 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/DateAdapter.kt @@ -0,0 +1,37 @@ +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.text.DateFormat +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +class DateAdapter(val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: Date?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): Date? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return formatter.parse(out.nextString()) + } + } + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..30ef6697183 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,35 @@ +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.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: LocalDate?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): LocalDate? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return LocalDate.parse(out.nextString(), formatter) + } + } + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..3ad781c66ca --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,35 @@ +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.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: LocalDateTime?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): LocalDateTime? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return LocalDateTime.parse(out.nextString(), formatter) + } + } + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..e615135c9cc --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,35 @@ +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.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: OffsetDateTime?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): OffsetDateTime? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return OffsetDateTime.parse(out.nextString(), formatter) + } + } + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/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-gson/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/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-gson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-gson/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..6465f148553 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,24 @@ +package org.openapitools.client.infrastructure + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.util.UUID +import java.util.Date + +object Serializer { + @JvmStatic + val gsonBuilder: GsonBuilder = GsonBuilder() + .registerTypeAdapter(Date::class.java, DateAdapter()) + .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) + .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) + .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) + .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) + + @JvmStatic + val gson: Gson by lazy { + gsonBuilder.create() + } +} diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..54df813fcee --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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.google.gson.annotations.SerializedName + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ + +data class ApiResponse ( + @SerializedName("code") + val code: kotlin.Int? = null, + @SerializedName("type") + val type: kotlin.String? = null, + @SerializedName("message") + val message: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..fdefa74fda0 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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.google.gson.annotations.SerializedName + +/** + * A category for a pet + * @param id + * @param name + */ + +data class Category ( + @SerializedName("id") + val id: kotlin.Long? = null, + @SerializedName("name") + val name: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..049c89df313 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.google.gson.annotations.SerializedName + +/** + * 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 ( + @SerializedName("id") + val id: kotlin.Long? = null, + @SerializedName("petId") + val petId: kotlin.Long? = null, + @SerializedName("quantity") + val quantity: kotlin.Int? = null, + @SerializedName("shipDate") + val shipDate: java.time.OffsetDateTime? = null, + /* Order Status */ + @SerializedName("status") + val status: Order.Status? = null, + @SerializedName("complete") + val complete: kotlin.Boolean? = null +) { + + /** + * Order Status + * Values: placed,approved,delivered + */ + + enum class Status(val value: kotlin.String){ + @SerializedName(value = "placed") placed("placed"), + @SerializedName(value = "approved") approved("approved"), + @SerializedName(value = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..af29ef2b61b --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Pet.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 org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.google.gson.annotations.SerializedName + +/** + * 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 ( + @SerializedName("name") + val name: kotlin.String, + @SerializedName("photoUrls") + val photoUrls: kotlin.collections.List, + @SerializedName("id") + val id: kotlin.Long? = null, + @SerializedName("category") + val category: Category? = null, + @SerializedName("tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + @SerializedName("status") + val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: available,pending,sold + */ + + enum class Status(val value: kotlin.String){ + @SerializedName(value = "available") available("available"), + @SerializedName(value = "pending") pending("pending"), + @SerializedName(value = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..28e82b1df68 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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.google.gson.annotations.SerializedName + +/** + * A tag for a pet + * @param id + * @param name + */ + +data class Tag ( + @SerializedName("id") + val id: kotlin.Long? = null, + @SerializedName("name") + val name: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..62baf33e927 --- /dev/null +++ b/samples/client/petstore/kotlin-gson/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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.google.gson.annotations.SerializedName + +/** + * 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 ( + @SerializedName("id") + val id: kotlin.Long? = null, + @SerializedName("username") + val username: kotlin.String? = null, + @SerializedName("firstName") + val firstName: kotlin.String? = null, + @SerializedName("lastName") + val lastName: kotlin.String? = null, + @SerializedName("email") + val email: kotlin.String? = null, + @SerializedName("password") + val password: kotlin.String? = null, + @SerializedName("phone") + val phone: kotlin.String? = null, + /* User Status */ + @SerializedName("userStatus") + val userStatus: kotlin.Int? = null +) + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/Application.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/Application.kt new file mode 100644 index 00000000000..a48b80eecd4 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/Application.kt @@ -0,0 +1,20 @@ +package org.openapitools + +import org.openapitools.client.apis.PetApi +import org.openapitools.client.apis.StoreApi +import org.openapitools.client.models.Category +import org.openapitools.client.models.Pet +import org.openapitools.client.models.Tag + +fun main() { + println(".main") + val inventory = StoreApi().getInventory() + println("Inventory : $inventory") + val pet = Pet(name = "Elliot", photoUrls = listOf("https://jameshooverstudios.com/wp-content/uploads/2015/04/Majestic-Dog-Photography-Elliot-Nov-5-2014.jpg", "https://express-images.franklymedia.com/6616/sites/981/2020/01/22105725/Elliott.jpg"), id = 123456453, category = Category(id = 13259476, name = "dog"), tags = listOf(Tag(id = 194093, name = "Elliot")), status = Pet.Status.AVAILABLE) + PetApi().addPet(pet) + val elliot = PetApi().getPetById(123456453) + println("Elliot : $elliot") + assert(pet == elliot) + println(".main") + +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..e4f7f4eeae0 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/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-jackson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..2c15d73b189 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(value)) + } + }.build() + } + mediaType == JsonMediaType -> Serializer.jacksonObjectMapper.writeValueAsString(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.jacksonObjectMapper.readValue(bodyContent, T::class.java) + 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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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.jacksonObjectMapper.writeValueAsString(value).replace("\"", "") + } +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-jackson/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/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-jackson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..fff39c7ac24 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,3 @@ +package org.openapitools.client.infrastructure + + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/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-jackson/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/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-jackson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-jackson/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..8b34e629c4e --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,18 @@ +package org.openapitools.client.infrastructure + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import java.util.Date + +object Serializer { + @JvmStatic + val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() + .registerModule(Jdk8Module()) + .registerModule(JavaTimeModule()) + .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) +} diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..c341f8ca321 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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.fasterxml.jackson.annotation.JsonProperty + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ + +data class ApiResponse ( + @field:JsonProperty("code") + val code: kotlin.Int? = null, + @field:JsonProperty("type") + val type: kotlin.String? = null, + @field:JsonProperty("message") + val message: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..2ed5390c1f3 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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.fasterxml.jackson.annotation.JsonProperty + +/** + * A category for a pet + * @param id + * @param name + */ + +data class Category ( + @field:JsonProperty("id") + val id: kotlin.Long? = null, + @field:JsonProperty("name") + val name: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..c7df5b55614 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.fasterxml.jackson.annotation.JsonProperty + +/** + * 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 ( + @field:JsonProperty("id") + val id: kotlin.Long? = null, + @field:JsonProperty("petId") + val petId: kotlin.Long? = null, + @field:JsonProperty("quantity") + val quantity: kotlin.Int? = null, + @field:JsonProperty("shipDate") + val shipDate: java.time.OffsetDateTime? = null, + /* Order Status */ + @field:JsonProperty("status") + val status: Order.Status? = null, + @field:JsonProperty("complete") + val complete: kotlin.Boolean? = null +) { + + /** + * Order Status + * Values: PLACED,APPROVED,DELIVERED + */ + + enum class Status(val value: kotlin.String){ + @JsonProperty(value = "placed") PLACED("placed"), + @JsonProperty(value = "approved") APPROVED("approved"), + @JsonProperty(value = "delivered") DELIVERED("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..be5b168e2d8 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Pet.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 org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * 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 ( + @field:JsonProperty("name") + val name: kotlin.String, + @field:JsonProperty("photoUrls") + val photoUrls: kotlin.collections.List, + @field:JsonProperty("id") + val id: kotlin.Long? = null, + @field:JsonProperty("category") + val category: Category? = null, + @field:JsonProperty("tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + @field:JsonProperty("status") + val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: AVAILABLE,PENDING,SOLD + */ + + enum class Status(val value: kotlin.String){ + @JsonProperty(value = "available") AVAILABLE("available"), + @JsonProperty(value = "pending") PENDING("pending"), + @JsonProperty(value = "sold") SOLD("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..7243f42ed7d --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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.fasterxml.jackson.annotation.JsonProperty + +/** + * A tag for a pet + * @param id + * @param name + */ + +data class Tag ( + @field:JsonProperty("id") + val id: kotlin.Long? = null, + @field:JsonProperty("name") + val name: kotlin.String? = null +) + diff --git a/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..e8f639e5092 --- /dev/null +++ b/samples/client/petstore/kotlin-jackson/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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.fasterxml.jackson.annotation.JsonProperty + +/** + * 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 ( + @field:JsonProperty("id") + val id: kotlin.Long? = null, + @field:JsonProperty("username") + val username: kotlin.String? = null, + @field:JsonProperty("firstName") + val firstName: kotlin.String? = null, + @field:JsonProperty("lastName") + val lastName: kotlin.String? = null, + @field:JsonProperty("email") + val email: kotlin.String? = null, + @field:JsonProperty("password") + val password: kotlin.String? = null, + @field:JsonProperty("phone") + val phone: kotlin.String? = null, + /* User Status */ + @field:JsonProperty("userStatus") + val userStatus: kotlin.Int? = null +) + diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..6685f0a73d4 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,376 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.OffsetDateTime?) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..a69de1961da --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,245 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } +} diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-string/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : 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-string/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-string/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/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-string/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..fafca8738f6 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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-string/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..a4c17c3b49d --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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-string/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..a66c335904e --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.OffsetDateTime? = 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-string/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..a3df06cb6eb --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Pet.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 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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-string/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..6e619023a5c --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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-string/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..af1e270325d --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..e4f7f4eeae0 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..e7f366d02cd --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : 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/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..06d9fe0bdc8 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,21 @@ +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(OffsetDateTimeAdapter()) + .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/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..18d2ce3dbbe --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..8396fa42357 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..d7091dd4c0c --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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.OffsetDateTime? = 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/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..8b4e6b44d4c --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..e7cdab2bb5d --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-moshi-codegen/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..1bfad844904 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/bin/main/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 +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-nonpublic/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..69cb6b35ef2 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 + +internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..4f8898adf9b --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 + +internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..725b36b0106 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 + +internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..d26cda9091c --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +internal typealias MultiValueMap = MutableMap> + +internal fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +internal val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +internal fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..473b3fd42ce --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +internal open class ApiClient(val baseUrl: String) { + internal 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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..c618544573e --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +internal enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +internal interface Response + +internal abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + abstract val statusCode: Int + abstract val headers: Map> +} + +internal class Success( + val data: T, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiInfrastructureResponse(ResponseType.Success) + +internal class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Informational) + +internal class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Redirection) + +internal class ClientError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.ClientError) + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..d7f9079c0d5 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..86bcb51fba6 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/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 + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..204b69dcb08 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/Errors.kt @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package org.openapitools.client.infrastructure + +import java.lang.RuntimeException + +internal open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + internal companion object { + private const val serialVersionUID: Long = 123L + } +} + +internal open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + internal companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..e86215d5717 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/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 + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..fe7069904ca --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/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 + +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..be7703c103d --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +internal class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..3e87d2c30f9 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/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. + */ +internal 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-nonpublic/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..e0fbb1e6526 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +internal enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..858d1b7339b --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Response + +/** + * Provides an extension to evaluation whether the response is a 1xx code + */ +internal val Response.isInformational : Boolean get() = this.code in 100..199 + +/** + * Provides an extension to evaluation whether the response is a 3xx code + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +internal val Response.isRedirect : Boolean get() = this.code in 300..399 + +/** + * Provides an extension to evaluation whether the response is a 4xx code + */ +internal 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 + */ +internal val Response.isServerError : Boolean get() = this.code in 500..999 diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..371e2a7013e --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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 + +internal object Serializer { + @JvmStatic + val moshiBuilder: Moshi.Builder = Moshi.Builder() + .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) + .add(OffsetDateTimeAdapter()) + .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-nonpublic/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..02fa692b57d --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/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 + +internal class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..a695278dfa3 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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 + */ + +internal 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-nonpublic/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..376994a9b25 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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 + */ + +internal 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-nonpublic/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..a943b97c1ea --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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 + */ + +internal 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.OffsetDateTime? = 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 + */ + + internal 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-nonpublic/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..544fab20f5a --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Pet.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 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 + */ + +internal data class Pet ( + @Json(name = "name") + val name: kotlin.String, + @Json(name = "photoUrls") + val photoUrls: kotlin.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: available,pending,sold + */ + + internal 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-nonpublic/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..d9b84e93eaf --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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 + */ + +internal 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-nonpublic/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..e0e821cd7e3 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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 + */ + +internal 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-nullable/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..ef80c520fd2 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List or null + * @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.collections.List) : kotlin.collections.List? { + 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.collections.List? + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List or null + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List? { + 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.collections.List? + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return Pet or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 or null + * @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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..b9dd7b38f59 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return kotlin.collections.Map or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..2ae5998489d --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return kotlin.String or null + * @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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..e7f366d02cd --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-nullable/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..77066de4e55 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-nullable/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-nullable/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-nullable/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/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-nullable/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..7d40c8efbc2 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,38 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..ceb0fbc8fe6 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,35 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..ed8f8b13a43 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Order.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 com.squareup.moshi.Json +import java.io.Serializable + +/** + * 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.OffsetDateTime? = null, + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + @Json(name = "complete") + val complete: kotlin.Boolean? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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-nullable/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..105f485f021 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Pet.kt @@ -0,0 +1,60 @@ +/** +* 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 java.io.Serializable + +/** + * 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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-nullable/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..944b1cd0a14 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,35 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..9697f07d5bf --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,54 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..e4f7f4eeae0 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..f60e40309bc --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,249 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Credentials +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.MediaType +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.ResponseBody +import okhttp3.Request +import okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> RequestBody.create( + MediaType.parse(mediaType), content + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.of( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = MediaType.parse(guessContentTypeFromFile(value)) + addPart(partHeaders, RequestBody.create(fileMediaType, value)) + } else { + val partHeaders = Headers.of( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + RequestBody.create(null, parameterToString(value)) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(value)) + } + }.build() + } + mediaType == JsonMediaType -> RequestBody.create( + MediaType.parse(mediaType), Serializer.moshi.adapter(T::class.java).toJson(content) + ) + 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 = HttpUrl.parse(baseUrl) ?: 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.message(), + response.body()?.string(), + response.code(), + response.headers().toMultimap() + ) + else -> return ServerError( + response.message(), + response.body()?.string(), + response.code(), + response.headers().toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-okhttp3/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..037fedbd18b --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-okhttp3/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-okhttp3/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/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-okhttp3/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..fafca8738f6 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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-okhttp3/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..a4c17c3b49d --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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-okhttp3/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..a66c335904e --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.OffsetDateTime? = 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-okhttp3/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..a3df06cb6eb --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Pet.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 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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-okhttp3/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..6e619023a5c --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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-okhttp3/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..af1e270325d --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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-retrofit2-rx3/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..b52cebf4c31 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,125 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import okhttp3.RequestBody +import io.reactivex.rxjava3.core.Single; +import io.reactivex.rxjava3.core.Completable; + +import org.openapitools.client.models.ApiResponse +import org.openapitools.client.models.Pet + +import okhttp3.MultipartBody + +interface PetApi { + /** + * Add a new pet to the store + * + * Responses: + * - 405: Invalid input + * + * @param body Pet object that needs to be added to the store + * @return [Call]<[Unit]> + */ + @POST("pet") + fun addPet(@Body body: Pet): Completable + + /** + * Deletes a pet + * + * Responses: + * - 400: Invalid pet value + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return [Call]<[Unit]> + */ + @DELETE("pet/{petId}") + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Completable + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * Responses: + * - 200: successful operation + * - 400: Invalid status value + * + * @param status Status values that need to be considered for filter + * @return [Call]<[kotlin.collections.List]> + */ + @GET("pet/findByStatus") + fun findPetsByStatus(@Query("status") status: CSVParams): Single> + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Responses: + * - 200: successful operation + * - 400: Invalid tag value + * + * @param tags Tags to filter by + * @return [Call]<[kotlin.collections.List]> + */ + @Deprecated("This api was deprecated") + @GET("pet/findByTags") + fun findPetsByTags(@Query("tags") tags: CSVParams): Single> + + /** + * Find pet by ID + * Returns a single pet + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Pet not found + * + * @param petId ID of pet to return + * @return [Call]<[Pet]> + */ + @GET("pet/{petId}") + fun getPetById(@Path("petId") petId: kotlin.Long): Single + + /** + * Update an existing pet + * + * Responses: + * - 400: Invalid ID supplied + * - 404: Pet not found + * - 405: Validation exception + * + * @param body Pet object that needs to be added to the store + * @return [Call]<[Unit]> + */ + @PUT("pet") + fun updatePet(@Body body: Pet): Completable + + /** + * Updates a pet in the store with form data + * + * Responses: + * - 405: Invalid input + * + * @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 [Call]<[Unit]> + */ + @FormUrlEncoded + @POST("pet/{petId}") + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Completable + + /** + * uploads an image + * + * Responses: + * - 200: successful operation + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return [Call]<[ApiResponse]> + */ + @Multipart + @POST("pet/{petId}/uploadImage") + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part): Single + +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..96603a0729a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,63 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import okhttp3.RequestBody +import io.reactivex.rxjava3.core.Single; +import io.reactivex.rxjava3.core.Completable; + +import org.openapitools.client.models.Order + +interface StoreApi { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Responses: + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of the order that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("store/order/{orderId}") + fun deleteOrder(@Path("orderId") orderId: kotlin.String): Completable + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * Responses: + * - 200: successful operation + * + * @return [Call]<[kotlin.collections.Map]> + */ + @GET("store/inventory") + fun getInventory(): Single> + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of pet that needs to be fetched + * @return [Call]<[Order]> + */ + @GET("store/order/{orderId}") + fun getOrderById(@Path("orderId") orderId: kotlin.Long): Single + + /** + * Place an order for a pet + * + * Responses: + * - 200: successful operation + * - 400: Invalid Order + * + * @param body order placed for purchasing the pet + * @return [Call]<[Order]> + */ + @POST("store/order") + fun placeOrder(@Body body: Order): Single + +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..4e04bc3627e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,114 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import okhttp3.RequestBody +import io.reactivex.rxjava3.core.Single; +import io.reactivex.rxjava3.core.Completable; + +import org.openapitools.client.models.User + +interface UserApi { + /** + * Create user + * This can only be done by the logged in user. + * Responses: + * - 0: successful operation + * + * @param body Created user object + * @return [Call]<[Unit]> + */ + @POST("user") + fun createUser(@Body body: User): Completable + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param body List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithArray") + fun createUsersWithArrayInput(@Body body: kotlin.collections.List): Completable + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param body List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithList") + fun createUsersWithListInput(@Body body: kotlin.collections.List): Completable + + /** + * Delete user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("user/{username}") + fun deleteUser(@Path("username") username: kotlin.String): Completable + + /** + * Get user by user name + * + * Responses: + * - 200: successful operation + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return [Call]<[User]> + */ + @GET("user/{username}") + fun getUserByName(@Path("username") username: kotlin.String): Single + + /** + * Logs user into the system + * + * Responses: + * - 200: successful operation + * - 400: Invalid username/password supplied + * + * @param username The user name for login + * @param password The password for login in clear text + * @return [Call]<[kotlin.String]> + */ + @GET("user/login") + fun loginUser(@Query("username") username: kotlin.String, @Query("password") password: kotlin.String): Single + + /** + * Logs out current logged in user session + * + * Responses: + * - 0: successful operation + * + * @return [Call]<[Unit]> + */ + @GET("user/logout") + fun logoutUser(): Completable + + /** + * Updated user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid user supplied + * - 404: User not found + * + * @param username name that need to be deleted + * @param body Updated user object + * @return [Call]<[Unit]> + */ + @PUT("user/{username}") + fun updateUser(@Path("username") username: kotlin.String, @Body body: User): Completable + +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 00000000000..524d5190ef8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,50 @@ +package org.openapitools.client.auth + +import java.io.IOException +import java.net.URI +import java.net.URISyntaxException + +import okhttp3.Interceptor +import okhttp3.Response + +class ApiKeyAuth( + private val location: String = "", + private val paramName: String = "", + private var apiKey: String = "" +) : Interceptor { + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + var request = chain.request() + + if ("query" == location) { + var newQuery = request.url.toUri().query + val paramValue = "$paramName=$apiKey" + if (newQuery == null) { + newQuery = paramValue + } else { + newQuery += "&$paramValue" + } + + val newUri: URI + try { + val oldUri = request.url.toUri() + newUri = URI(oldUri.scheme, oldUri.authority, + oldUri.path, newQuery, oldUri.fragment) + } catch (e: URISyntaxException) { + throw IOException(e) + } + + request = request.newBuilder().url(newUri.toURL()).build() + } else if ("header" == location) { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build() + } else if ("cookie" == location) { + request = request.newBuilder() + .addHeader("Cookie", "$paramName=$apiKey") + .build() + } + return chain.proceed(request) + } +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 00000000000..311a8f43979 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,151 @@ +package org.openapitools.client.auth + +import java.net.HttpURLConnection.HTTP_UNAUTHORIZED +import java.net.HttpURLConnection.HTTP_FORBIDDEN + +import java.io.IOException + +import org.apache.oltu.oauth2.client.OAuthClient +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException +import org.apache.oltu.oauth2.common.message.types.GrantType +import org.apache.oltu.oauth2.common.token.BasicOAuthToken + +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Response + +class OAuth( + client: OkHttpClient, + var tokenRequestBuilder: TokenRequestBuilder +) : Interceptor { + + interface AccessTokenListener { + fun notify(token: BasicOAuthToken) + } + + private var oauthClient: OAuthClient = OAuthClient(OAuthOkHttpClient(client)) + + @Volatile + private var accessToken: String? = null + var authenticationRequestBuilder: AuthenticationRequestBuilder? = null + private var accessTokenListener: AccessTokenListener? = null + + constructor( + requestBuilder: TokenRequestBuilder + ) : this( + OkHttpClient(), + requestBuilder + ) + + constructor( + flow: OAuthFlow, + authorizationUrl: String, + tokenUrl: String, + scopes: String + ) : this( + OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes) + ) { + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + fun setFlow(flow: OAuthFlow) { + when (flow) { + OAuthFlow.accessCode, OAuthFlow.implicit -> + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE) + OAuthFlow.password -> + tokenRequestBuilder.setGrantType(GrantType.PASSWORD) + OAuthFlow.application -> + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS) + } + } + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + return retryingIntercept(chain, true) + } + + @Throws(IOException::class) + private fun retryingIntercept(chain: Interceptor.Chain, updateTokenAndRetryOnAuthorizationFailure: Boolean): Response { + var request = chain.request() + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request) + } + + // If first time, get the token + val oAuthRequest: OAuthClientRequest + if (accessToken == null) { + updateAccessToken(null) + } + + if (accessToken != null) { + // Build the request + val rb = request.newBuilder() + + val requestAccessToken = accessToken + try { + oAuthRequest = OAuthBearerClientRequest(request.url.toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage() + } catch (e: OAuthSystemException) { + throw IOException(e) + } + + oAuthRequest.headers.entries.forEach { header -> + rb.addHeader(header.key, header.value) + } + rb.url(oAuthRequest.locationUri) + + //Execute the request + val response = chain.proceed(rb.build()) + + // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row. + if ((response.code == HTTP_UNAUTHORIZED || response.code == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) { + try { + if (updateAccessToken(requestAccessToken)) { + response.body?.close() + return retryingIntercept(chain, false) + } + } catch (e: Exception) { + response.body?.close() + throw e + } + } + return response + } else { + return chain.proceed(chain.request()) + } + } + + /** + * Returns true if the access token has been updated + */ + @Throws(IOException::class) + @Synchronized + fun updateAccessToken(requestAccessToken: String?): Boolean { + if (accessToken == null || accessToken.equals(requestAccessToken)) { + return try { + val accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()) + if (accessTokenResponse != null && accessTokenResponse.accessToken != null) { + accessToken = accessTokenResponse.accessToken + accessTokenListener?.notify(accessTokenResponse.oAuthToken as BasicOAuthToken) + !accessToken.equals(requestAccessToken) + } else { + false + } + } catch (e: OAuthSystemException) { + throw IOException(e) + } catch (e: OAuthProblemException) { + throw IOException(e) + } + } + return true; + } +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthFlow.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthFlow.kt new file mode 100644 index 00000000000..bcada9b7a6a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthFlow.kt @@ -0,0 +1,5 @@ +package org.openapitools.client.auth + +enum class OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt new file mode 100644 index 00000000000..93adbda3fc9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -0,0 +1,61 @@ +package org.openapitools.client.auth + +import java.io.IOException + +import org.apache.oltu.oauth2.client.HttpClient +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.response.OAuthClientResponse +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException + +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.RequestBody + + +class OAuthOkHttpClient( + private var client: OkHttpClient +) : HttpClient { + + constructor() : this(OkHttpClient()) + + @Throws(OAuthSystemException::class, OAuthProblemException::class) + override fun execute( + request: OAuthClientRequest, + headers: Map?, + requestMethod: String, + responseClass: Class?): T { + + var mediaType = "application/json".toMediaTypeOrNull() + val requestBuilder = Request.Builder().url(request.locationUri) + + headers?.forEach { entry -> + if (entry.key.equals("Content-Type", true)) { + mediaType = entry.value.toMediaTypeOrNull() + } else { + requestBuilder.addHeader(entry.key, entry.value) + } + } + + val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + requestBuilder.method(requestMethod, body) + + try { + val response = client.newCall(requestBuilder.build()).execute() + return OAuthClientResponseFactory.createCustomResponse( + response.body?.string(), + response.body?.contentType()?.toString(), + response.code, + responseClass) + } catch (e: IOException) { + throw OAuthSystemException(e) + } + } + + override fun shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..e3962e0c0f2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,204 @@ +package org.openapitools.client.infrastructure + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.openapitools.client.auth.ApiKeyAuth +import org.openapitools.client.auth.OAuth +import org.openapitools.client.auth.OAuth.AccessTokenListener +import org.openapitools.client.auth.OAuthFlow + +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.converter.scalars.ScalarsConverterFactory +import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory +import com.squareup.moshi.Moshi +import retrofit2.converter.moshi.MoshiConverterFactory + +class ApiClient( + private var baseUrl: String = defaultBasePath, + private val okHttpClientBuilder: OkHttpClient.Builder? = null, + private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + private val okHttpClient : OkHttpClient? = null +) { + private val apiAuthorizations = mutableMapOf() + var logger: ((String) -> Unit)? = null + + private val retrofitBuilder: Retrofit.Builder by lazy { + Retrofit.Builder() + .baseUrl(baseUrl) + .addConverterFactory(ScalarsConverterFactory.create()) + + .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) + .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) + } + + private val clientBuilder: OkHttpClient.Builder by lazy { + okHttpClientBuilder ?: defaultClientBuilder + } + + private val defaultClientBuilder: OkHttpClient.Builder by lazy { + OkHttpClient() + .newBuilder() + .addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { + override fun log(message: String) { + logger?.invoke(message) + } + }).apply { + level = HttpLoggingInterceptor.Level.BODY + }) + } + + init { + normalizeBaseUrl() + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + authNames: Array + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { + authNames.forEach { authName -> + val auth = when (authName) { + "api_key" -> ApiKeyAuth("header", "api_key")"petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") + else -> throw RuntimeException("auth name $authName not found in available auth names") + } + addAuthorization(authName, auth); + } + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + authName: String, + clientId: String, + secret: String, + username: String, + password: String + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder, arrayOf(authName)) { + getTokenEndPoint() + ?.setClientId(clientId) + ?.setClientSecret(secret) + ?.setUsername(username) + ?.setPassword(password) + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Token request builder + */ + fun getTokenEndPoint(): TokenRequestBuilder? { + var result: TokenRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = tokenRequestBuilder + } + return result + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Authentication request builder + */ + fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? { + var result: AuthenticationRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = authenticationRequestBuilder + } + return result + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken Access token + * @return ApiClient + */ + fun setAccessToken(accessToken: String): ApiClient { + apiAuthorizations.values.runOnFirst { + setAccessToken(accessToken) + } + return this + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI + * @return ApiClient + */ + fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient { + apiAuthorizations.values.runOnFirst { + tokenRequestBuilder + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI) + authenticationRequestBuilder + ?.setClientId(clientId) + ?.setRedirectURI(redirectURI) + } + return this; + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener Access token listener + * @return ApiClient + */ + fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient { + apiAuthorizations.values.runOnFirst { + registerAccessTokenListener(accessTokenListener) + } + return this; + } + + /** + * Adds an authorization to be used by the client + * @param authName Authentication name + * @param authorization Authorization interceptor + * @return ApiClient + */ + fun addAuthorization(authName: String, authorization: Interceptor): ApiClient { + if (apiAuthorizations.containsKey(authName)) { + throw RuntimeException("auth name $authName already in api authorizations") + } + apiAuthorizations[authName] = authorization + clientBuilder.addInterceptor(authorization) + return this + } + + fun setLogger(logger: (String) -> Unit): ApiClient { + this.logger = logger + return this + } + + fun createService(serviceClass: Class): S { + var usedClient: OkHttpClient? = null + this.okHttpClient?.let { usedClient = it } ?: run {usedClient = clientBuilder.build()} + return retrofitBuilder.client(usedClient).build().create(serviceClass) + } + + private fun normalizeBaseUrl() { + if (!baseUrl.endsWith("/")) { + baseUrl += "/" + } + } + + private inline fun Iterable.runOnFirst(callback: U.() -> Unit) { + for (element in this) { + if (element is U) { + callback.invoke(element) + break + } + } + } + + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/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-rx3/bin/main/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/CollectionFormats.kt new file mode 100644 index 00000000000..001e99325d2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/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-rx3/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/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-rx3/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/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-rx3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt new file mode 100644 index 00000000000..1804d1ae2bb --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.JsonDataException +import com.squareup.moshi.Moshi +import retrofit2.Response + +@Throws(JsonDataException::class) +inline fun Response<*>.getErrorResponse(serializerBuilder: Moshi.Builder = Serializer.moshiBuilder): T? { + val serializer = serializerBuilder.build() + val parser = serializer.adapter(T::class.java) + val response = errorBody()?.string() + if(response != null) { + return parser.fromJson(response) + } + return null +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-rx3/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/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-rx3/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..fafca8738f6 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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-rx3/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..a4c17c3b49d --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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-rx3/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..a66c335904e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.OffsetDateTime? = 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-rx3/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..a3df06cb6eb --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Pet.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 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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-rx3/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..6e619023a5c --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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-rx3/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..af1e270325d --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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-retrofit2/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..4d78248129c --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,124 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody + +import org.openapitools.client.models.ApiResponse +import org.openapitools.client.models.Pet + +import okhttp3.MultipartBody + +interface PetApi { + /** + * Add a new pet to the store + * + * Responses: + * - 405: Invalid input + * + * @param body Pet object that needs to be added to the store + * @return [Call]<[Unit]> + */ + @POST("pet") + fun addPet(@Body body: Pet): Call + + /** + * Deletes a pet + * + * Responses: + * - 400: Invalid pet value + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return [Call]<[Unit]> + */ + @DELETE("pet/{petId}") + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * Responses: + * - 200: successful operation + * - 400: Invalid status value + * + * @param status Status values that need to be considered for filter + * @return [Call]<[kotlin.collections.List]> + */ + @GET("pet/findByStatus") + fun findPetsByStatus(@Query("status") status: CSVParams): Call> + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Responses: + * - 200: successful operation + * - 400: Invalid tag value + * + * @param tags Tags to filter by + * @return [Call]<[kotlin.collections.List]> + */ + @Deprecated("This api was deprecated") + @GET("pet/findByTags") + fun findPetsByTags(@Query("tags") tags: CSVParams): Call> + + /** + * Find pet by ID + * Returns a single pet + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Pet not found + * + * @param petId ID of pet to return + * @return [Call]<[Pet]> + */ + @GET("pet/{petId}") + fun getPetById(@Path("petId") petId: kotlin.Long): Call + + /** + * Update an existing pet + * + * Responses: + * - 400: Invalid ID supplied + * - 404: Pet not found + * - 405: Validation exception + * + * @param body Pet object that needs to be added to the store + * @return [Call]<[Unit]> + */ + @PUT("pet") + fun updatePet(@Body body: Pet): Call + + /** + * Updates a pet in the store with form data + * + * Responses: + * - 405: Invalid input + * + * @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 [Call]<[Unit]> + */ + @FormUrlEncoded + @POST("pet/{petId}") + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Call + + /** + * uploads an image + * + * Responses: + * - 200: successful operation + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return [Call]<[ApiResponse]> + */ + @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/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..45b6d20b1c7 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,62 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody + +import org.openapitools.client.models.Order + +interface StoreApi { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Responses: + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of the order that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("store/order/{orderId}") + fun deleteOrder(@Path("orderId") orderId: kotlin.String): Call + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * Responses: + * - 200: successful operation + * + * @return [Call]<[kotlin.collections.Map]> + */ + @GET("store/inventory") + fun getInventory(): Call> + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of pet that needs to be fetched + * @return [Call]<[Order]> + */ + @GET("store/order/{orderId}") + fun getOrderById(@Path("orderId") orderId: kotlin.Long): Call + + /** + * Place an order for a pet + * + * Responses: + * - 200: successful operation + * - 400: Invalid Order + * + * @param body order placed for purchasing the pet + * @return [Call]<[Order]> + */ + @POST("store/order") + fun placeOrder(@Body body: Order): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..33f031ec714 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,113 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody + +import org.openapitools.client.models.User + +interface UserApi { + /** + * Create user + * This can only be done by the logged in user. + * Responses: + * - 0: successful operation + * + * @param body Created user object + * @return [Call]<[Unit]> + */ + @POST("user") + fun createUser(@Body body: User): Call + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param body List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithArray") + fun createUsersWithArrayInput(@Body body: kotlin.collections.List): Call + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param body List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithList") + fun createUsersWithListInput(@Body body: kotlin.collections.List): Call + + /** + * Delete user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("user/{username}") + fun deleteUser(@Path("username") username: kotlin.String): Call + + /** + * Get user by user name + * + * Responses: + * - 200: successful operation + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return [Call]<[User]> + */ + @GET("user/{username}") + fun getUserByName(@Path("username") username: kotlin.String): Call + + /** + * Logs user into the system + * + * Responses: + * - 200: successful operation + * - 400: Invalid username/password supplied + * + * @param username The user name for login + * @param password The password for login in clear text + * @return [Call]<[kotlin.String]> + */ + @GET("user/login") + fun loginUser(@Query("username") username: kotlin.String, @Query("password") password: kotlin.String): Call + + /** + * Logs out current logged in user session + * + * Responses: + * - 0: successful operation + * + * @return [Call]<[Unit]> + */ + @GET("user/logout") + fun logoutUser(): Call + + /** + * Updated user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid user supplied + * - 404: User not found + * + * @param username name that need to be deleted + * @param body Updated user object + * @return [Call]<[Unit]> + */ + @PUT("user/{username}") + fun updateUser(@Path("username") username: kotlin.String, @Body body: User): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 00000000000..524d5190ef8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,50 @@ +package org.openapitools.client.auth + +import java.io.IOException +import java.net.URI +import java.net.URISyntaxException + +import okhttp3.Interceptor +import okhttp3.Response + +class ApiKeyAuth( + private val location: String = "", + private val paramName: String = "", + private var apiKey: String = "" +) : Interceptor { + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + var request = chain.request() + + if ("query" == location) { + var newQuery = request.url.toUri().query + val paramValue = "$paramName=$apiKey" + if (newQuery == null) { + newQuery = paramValue + } else { + newQuery += "&$paramValue" + } + + val newUri: URI + try { + val oldUri = request.url.toUri() + newUri = URI(oldUri.scheme, oldUri.authority, + oldUri.path, newQuery, oldUri.fragment) + } catch (e: URISyntaxException) { + throw IOException(e) + } + + request = request.newBuilder().url(newUri.toURL()).build() + } else if ("header" == location) { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build() + } else if ("cookie" == location) { + request = request.newBuilder() + .addHeader("Cookie", "$paramName=$apiKey") + .build() + } + return chain.proceed(request) + } +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 00000000000..311a8f43979 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,151 @@ +package org.openapitools.client.auth + +import java.net.HttpURLConnection.HTTP_UNAUTHORIZED +import java.net.HttpURLConnection.HTTP_FORBIDDEN + +import java.io.IOException + +import org.apache.oltu.oauth2.client.OAuthClient +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException +import org.apache.oltu.oauth2.common.message.types.GrantType +import org.apache.oltu.oauth2.common.token.BasicOAuthToken + +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Response + +class OAuth( + client: OkHttpClient, + var tokenRequestBuilder: TokenRequestBuilder +) : Interceptor { + + interface AccessTokenListener { + fun notify(token: BasicOAuthToken) + } + + private var oauthClient: OAuthClient = OAuthClient(OAuthOkHttpClient(client)) + + @Volatile + private var accessToken: String? = null + var authenticationRequestBuilder: AuthenticationRequestBuilder? = null + private var accessTokenListener: AccessTokenListener? = null + + constructor( + requestBuilder: TokenRequestBuilder + ) : this( + OkHttpClient(), + requestBuilder + ) + + constructor( + flow: OAuthFlow, + authorizationUrl: String, + tokenUrl: String, + scopes: String + ) : this( + OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes) + ) { + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + fun setFlow(flow: OAuthFlow) { + when (flow) { + OAuthFlow.accessCode, OAuthFlow.implicit -> + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE) + OAuthFlow.password -> + tokenRequestBuilder.setGrantType(GrantType.PASSWORD) + OAuthFlow.application -> + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS) + } + } + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + return retryingIntercept(chain, true) + } + + @Throws(IOException::class) + private fun retryingIntercept(chain: Interceptor.Chain, updateTokenAndRetryOnAuthorizationFailure: Boolean): Response { + var request = chain.request() + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request) + } + + // If first time, get the token + val oAuthRequest: OAuthClientRequest + if (accessToken == null) { + updateAccessToken(null) + } + + if (accessToken != null) { + // Build the request + val rb = request.newBuilder() + + val requestAccessToken = accessToken + try { + oAuthRequest = OAuthBearerClientRequest(request.url.toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage() + } catch (e: OAuthSystemException) { + throw IOException(e) + } + + oAuthRequest.headers.entries.forEach { header -> + rb.addHeader(header.key, header.value) + } + rb.url(oAuthRequest.locationUri) + + //Execute the request + val response = chain.proceed(rb.build()) + + // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row. + if ((response.code == HTTP_UNAUTHORIZED || response.code == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) { + try { + if (updateAccessToken(requestAccessToken)) { + response.body?.close() + return retryingIntercept(chain, false) + } + } catch (e: Exception) { + response.body?.close() + throw e + } + } + return response + } else { + return chain.proceed(chain.request()) + } + } + + /** + * Returns true if the access token has been updated + */ + @Throws(IOException::class) + @Synchronized + fun updateAccessToken(requestAccessToken: String?): Boolean { + if (accessToken == null || accessToken.equals(requestAccessToken)) { + return try { + val accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()) + if (accessTokenResponse != null && accessTokenResponse.accessToken != null) { + accessToken = accessTokenResponse.accessToken + accessTokenListener?.notify(accessTokenResponse.oAuthToken as BasicOAuthToken) + !accessToken.equals(requestAccessToken) + } else { + false + } + } catch (e: OAuthSystemException) { + throw IOException(e) + } catch (e: OAuthProblemException) { + throw IOException(e) + } + } + return true; + } +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthFlow.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthFlow.kt new file mode 100644 index 00000000000..bcada9b7a6a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthFlow.kt @@ -0,0 +1,5 @@ +package org.openapitools.client.auth + +enum class OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt new file mode 100644 index 00000000000..93adbda3fc9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -0,0 +1,61 @@ +package org.openapitools.client.auth + +import java.io.IOException + +import org.apache.oltu.oauth2.client.HttpClient +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.response.OAuthClientResponse +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException + +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.RequestBody + + +class OAuthOkHttpClient( + private var client: OkHttpClient +) : HttpClient { + + constructor() : this(OkHttpClient()) + + @Throws(OAuthSystemException::class, OAuthProblemException::class) + override fun execute( + request: OAuthClientRequest, + headers: Map?, + requestMethod: String, + responseClass: Class?): T { + + var mediaType = "application/json".toMediaTypeOrNull() + val requestBuilder = Request.Builder().url(request.locationUri) + + headers?.forEach { entry -> + if (entry.key.equals("Content-Type", true)) { + mediaType = entry.value.toMediaTypeOrNull() + } else { + requestBuilder.addHeader(entry.key, entry.value) + } + } + + val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + requestBuilder.method(requestMethod, body) + + try { + val response = client.newCall(requestBuilder.build()).execute() + return OAuthClientResponseFactory.createCustomResponse( + response.body?.string(), + response.body?.contentType()?.toString(), + response.code, + responseClass) + } catch (e: IOException) { + throw OAuthSystemException(e) + } + } + + override fun shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..8f822585a6e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,201 @@ +package org.openapitools.client.infrastructure + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.openapitools.client.auth.ApiKeyAuth +import org.openapitools.client.auth.OAuth +import org.openapitools.client.auth.OAuth.AccessTokenListener +import org.openapitools.client.auth.OAuthFlow + +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.converter.scalars.ScalarsConverterFactory +import com.squareup.moshi.Moshi +import retrofit2.converter.moshi.MoshiConverterFactory + +class ApiClient( + private var baseUrl: String = defaultBasePath, + private val okHttpClientBuilder: OkHttpClient.Builder? = null, + private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + private val okHttpClient : OkHttpClient? = null +) { + private val apiAuthorizations = mutableMapOf() + var logger: ((String) -> Unit)? = null + + private val retrofitBuilder: Retrofit.Builder by lazy { + Retrofit.Builder() + .baseUrl(baseUrl) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) + } + + private val clientBuilder: OkHttpClient.Builder by lazy { + okHttpClientBuilder ?: defaultClientBuilder + } + + private val defaultClientBuilder: OkHttpClient.Builder by lazy { + OkHttpClient() + .newBuilder() + .addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { + override fun log(message: String) { + logger?.invoke(message) + } + }).apply { + level = HttpLoggingInterceptor.Level.BODY + }) + } + + init { + normalizeBaseUrl() + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + authNames: Array + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { + authNames.forEach { authName -> + val auth = when (authName) { + "api_key" -> ApiKeyAuth("header", "api_key")"petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") + else -> throw RuntimeException("auth name $authName not found in available auth names") + } + addAuthorization(authName, auth); + } + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, + authName: String, + clientId: String, + secret: String, + username: String, + password: String + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder, arrayOf(authName)) { + getTokenEndPoint() + ?.setClientId(clientId) + ?.setClientSecret(secret) + ?.setUsername(username) + ?.setPassword(password) + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Token request builder + */ + fun getTokenEndPoint(): TokenRequestBuilder? { + var result: TokenRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = tokenRequestBuilder + } + return result + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Authentication request builder + */ + fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? { + var result: AuthenticationRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = authenticationRequestBuilder + } + return result + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken Access token + * @return ApiClient + */ + fun setAccessToken(accessToken: String): ApiClient { + apiAuthorizations.values.runOnFirst { + setAccessToken(accessToken) + } + return this + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI + * @return ApiClient + */ + fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient { + apiAuthorizations.values.runOnFirst { + tokenRequestBuilder + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI) + authenticationRequestBuilder + ?.setClientId(clientId) + ?.setRedirectURI(redirectURI) + } + return this; + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener Access token listener + * @return ApiClient + */ + fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient { + apiAuthorizations.values.runOnFirst { + registerAccessTokenListener(accessTokenListener) + } + return this; + } + + /** + * Adds an authorization to be used by the client + * @param authName Authentication name + * @param authorization Authorization interceptor + * @return ApiClient + */ + fun addAuthorization(authName: String, authorization: Interceptor): ApiClient { + if (apiAuthorizations.containsKey(authName)) { + throw RuntimeException("auth name $authName already in api authorizations") + } + apiAuthorizations[authName] = authorization + clientBuilder.addInterceptor(authorization) + return this + } + + fun setLogger(logger: (String) -> Unit): ApiClient { + this.logger = logger + return this + } + + fun createService(serviceClass: Class): S { + var usedClient: OkHttpClient? = null + this.okHttpClient?.let { usedClient = it } ?: run {usedClient = clientBuilder.build()} + return retrofitBuilder.client(usedClient).build().create(serviceClass) + } + + private fun normalizeBaseUrl() { + if (!baseUrl.endsWith("/")) { + baseUrl += "/" + } + } + + private inline fun Iterable.runOnFirst(callback: U.() -> Unit) { + for (element in this) { + if (element is U) { + callback.invoke(element) + break + } + } + } + + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/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/bin/main/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/CollectionFormats.kt new file mode 100644 index 00000000000..001e99325d2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/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/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/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/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/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/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt new file mode 100644 index 00000000000..1804d1ae2bb --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/ResponseExt.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.JsonDataException +import com.squareup.moshi.Moshi +import retrofit2.Response + +@Throws(JsonDataException::class) +inline fun Response<*>.getErrorResponse(serializerBuilder: Moshi.Builder = Serializer.moshiBuilder): T? { + val serializer = serializerBuilder.build() + val parser = serializer.adapter(T::class.java) + val response = errorBody()?.string() + if(response != null) { + return parser.fromJson(response) + } + return null +} diff --git a/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/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/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..fafca8738f6 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..a4c17c3b49d --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..a66c335904e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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.OffsetDateTime? = 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/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..a3df06cb6eb --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Pet.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 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..6e619023a5c --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..af1e270325d --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..da9784198d1 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Deletes a pet + * + * @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(apiKey: kotlin.String?, petId: kotlin.Long) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..e7f366d02cd --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-string/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..87437871a31 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-string/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/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-string/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..7d40c8efbc2 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,38 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..ceb0fbc8fe6 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,35 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..ec768d1acef --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Order.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 com.squareup.moshi.Json +import java.io.Serializable + +/** + * 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: kotlin.String? = null, + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + @Json(name = "complete") + val complete: kotlin.Boolean? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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-string/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..66667bf07cd --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Pet.kt @@ -0,0 +1,60 @@ +/** +* 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 java.io.Serializable + +/** + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ + +data class Pet ( + @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.collections.List, + @Json(name = "tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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-string/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..944b1cd0a14 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,35 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..9697f07d5bf --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,54 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-string/bin/test/org/openapitools/client/PetApiTest.kt b/samples/client/petstore/kotlin-string/bin/test/org/openapitools/client/PetApiTest.kt new file mode 100644 index 00000000000..5ae1468ad07 --- /dev/null +++ b/samples/client/petstore/kotlin-string/bin/test/org/openapitools/client/PetApiTest.kt @@ -0,0 +1,104 @@ +package org.openapitools.client + +import io.kotlintest.shouldBe +import io.kotlintest.matchers.numerics.shouldBeGreaterThan +import io.kotlintest.matchers.string.shouldContain +import io.kotlintest.shouldThrow +import io.kotlintest.specs.ShouldSpec +import org.openapitools.client.apis.PetApi +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.models.Category +import org.openapitools.client.models.Pet +import org.openapitools.client.models.Tag + +class PetApiTest : ShouldSpec() { + init { + + val petId:Long = 10006 + val api = PetApi() + + should("add a pet") { + + val pet = Pet( + id = petId, + name = "kotlin client test", + photoUrls = listOf("http://test_kotlin_unit_test.com"), + category = Category(petId, "test kotlin category"), + tags = listOf(Tag(petId, "test kotlin tag")) + ) + api.addPet(pet) + + } + + should("get pet by id") { + val result = api.getPetById(petId) + + result.id shouldBe (petId) + result.name shouldBe ("kotlin client test") + result.photoUrls[0] shouldBe ("http://test_kotlin_unit_test.com") + result.category!!.id shouldBe (petId) + result.category!!.name shouldBe ("test kotlin category") + result.tags!![0].id shouldBe (petId) + result.tags!![0].name shouldBe ("test kotlin tag") + + } + + should("find pet by status") { + val result = api.findPetsByStatus(listOf("available")) + + result.size.shouldBeGreaterThan(0) + + for(onePet in result) { + onePet.status.shouldBe(Pet.Status.available) + } + + val result2 = api.findPetsByStatus(listOf("unknown_and_incorrect_status")) + + result2.size.shouldBe(0) + + } + + should("update a pet") { + val pet = Pet( + id = petId, + name = "kotlin client updatePet", + status = Pet.Status.pending, + photoUrls = listOf("http://test_kotlin_unit_test.com") + ) + api.updatePet(pet) + + // verify updated Pet + val result = api.getPetById(petId) + result.id shouldBe (petId) + result.name shouldBe ("kotlin client updatePet") + result.status shouldBe (Pet.Status.pending) + + } + + should("update a pet with form") { + val name = "kotlin client updatePet with Form" + val status = "pending" + + api.updatePetWithForm(petId, name, status) + + // verify updated Pet + val result = api.getPetById(petId) + result.id shouldBe (petId) + result.name shouldBe ("kotlin client updatePet with Form") + result.status shouldBe (Pet.Status.pending) + + } + + should("delete a pet") { + api.deletePet("apiKey", petId) + + // verify updated Pet + val exception = shouldThrow { + api.getPetById(petId) + } + exception.message?.shouldContain("Pet not found") + } + + } + +} diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..e4f7f4eeae0 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,374 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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() + apiKey?.apply { localVariableHeaders["api_key"] = this.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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List + * @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) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + 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.collections.List + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "application/x-www-form-urlencoded") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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 "multipart/form-data") + 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..08822c67e32 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,198 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..258a2540e9e --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,363 @@ +/** +* 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 = defaultBasePath) : ApiClient(basePath) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2") + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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.collections.List) : 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * 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("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..cb540f6ebd7 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,251 @@ +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 okhttp3.Headers +import okhttp3.MultipartBody +import java.io.File +import java.net.URLConnection +import java.util.Date +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDateTime +import org.threeten.bp.LocalTime +import org.threeten.bp.OffsetDateTime +import org.threeten.bp.OffsetTime + +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() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType -> { + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + if (value is File) { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"; filename=\"${value.name}\"" + ) + val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() + addPart(partHeaders, value.asRequestBody(fileMediaType)) + } else { + val partHeaders = Headers.headersOf( + "Content-Disposition", + "form-data; name=\"$key\"" + ) + addPart( + partHeaders, + parameterToString(value).toRequestBody(null) + ) + } + } + }.build() + } + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, parameterToString(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.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String { + when (value) { + null -> { + return "" + } + is Array<*> -> { + return toMultiValue(value, "csv").toString() + } + is Iterable<*> -> { + return toMultiValue(value, "csv").toString() + } + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { + return parseDateToQueryString(value) + } + else -> { + return value.toString() + } + } + } + + 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-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..9dc8d8dbbfa --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiInfrastructureResponse(val responseType: ResponseType): Response { + 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 message: String? = null, + 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-threetenbp/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..b5310e71f13 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..ff5439aeb42 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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 org.threeten.bp.LocalDate +import org.threeten.bp.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-threetenbp/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..710a9cc1317 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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 org.threeten.bp.LocalDateTime +import org.threeten.bp.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-threetenbp/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 00000000000..28b3eb3cd70 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import org.threeten.bp.OffsetDateTime +import org.threeten.bp.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..9bd2790dc14 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +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 + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +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-threetenbp/bin/main/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..697559b2ec1 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,23 @@ +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(OffsetDateTimeAdapter()) + .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-threetenbp/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/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-threetenbp/bin/main/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..fafca8738f6 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* 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-threetenbp/bin/main/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..a4c17c3b49d --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Category.kt @@ -0,0 +1,29 @@ +/** +* 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-threetenbp/bin/main/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..300f94d8545 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Order.kt @@ -0,0 +1,54 @@ +/** +* 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: org.threeten.bp.OffsetDateTime? = 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-threetenbp/bin/main/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..a3df06cb6eb --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Pet.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 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.collections.List, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.collections.List? = 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-threetenbp/bin/main/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..6e619023a5c --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/Tag.kt @@ -0,0 +1,29 @@ +/** +* 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-threetenbp/bin/main/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..af1e270325d --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/main/org/openapitools/client/models/User.kt @@ -0,0 +1,48 @@ +/** +* 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-threetenbp/bin/test/org/openapitools/client/PetApiTest.kt b/samples/client/petstore/kotlin-threetenbp/bin/test/org/openapitools/client/PetApiTest.kt new file mode 100644 index 00000000000..5da4f9082a8 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/bin/test/org/openapitools/client/PetApiTest.kt @@ -0,0 +1,104 @@ +package org.openapitools.client + +import io.kotlintest.shouldBe +import io.kotlintest.matchers.numerics.shouldBeGreaterThan +import io.kotlintest.matchers.string.shouldContain +import io.kotlintest.shouldThrow +import io.kotlintest.specs.ShouldSpec +import org.openapitools.client.apis.PetApi +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.models.Category +import org.openapitools.client.models.Pet +import org.openapitools.client.models.Tag + +class PetApiTest : ShouldSpec() { + init { + + val petId:Long = 10006 + val api = PetApi() + + should("add a pet") { + + val pet = Pet( + id = petId, + name = "kotlin client test", + photoUrls = listOf("http://test_kotlin_unit_test.com"), + category = Category(petId, "test kotlin category"), + tags = listOf(Tag(petId, "test kotlin tag")) + ) + api.addPet(pet) + + } + + should("get pet by id") { + val result = api.getPetById(petId) + + result.id shouldBe (petId) + result.name shouldBe ("kotlin client test") + result.photoUrls[0] shouldBe ("http://test_kotlin_unit_test.com") + result.category!!.id shouldBe (petId) + result.category!!.name shouldBe ("test kotlin category") + result.tags!![0].id shouldBe (petId) + result.tags!![0].name shouldBe ("test kotlin tag") + + } + + should("find pet by status") { + val result = api.findPetsByStatus(listOf("available")) + + result.size.shouldBeGreaterThan(0) + + for(onePet in result) { + onePet.status.shouldBe(Pet.Status.available) + } + + val result2 = api.findPetsByStatus(listOf("unknown_and_incorrect_status")) + + result2.size.shouldBe(0) + + } + + should("update a pet") { + val pet = Pet( + id = petId, + name = "kotlin client updatePet", + status = Pet.Status.pending, + photoUrls = listOf("http://test_kotlin_unit_test.com") + ) + api.updatePet(pet) + + // verify updated Pet + val result = api.getPetById(petId) + result.id shouldBe (petId) + result.name shouldBe ("kotlin client updatePet") + result.status shouldBe (Pet.Status.pending) + + } + + should("update a pet with form") { + val name = "kotlin client updatePet with Form" + val status = "pending" + + api.updatePetWithForm(petId, name, status) + + // verify updated Pet + val result = api.getPetById(petId) + result.id shouldBe (petId) + result.name shouldBe ("kotlin client updatePet with Form") + result.status shouldBe (Pet.Status.pending) + + } + + should("delete a pet") { + api.deletePet(petId, "apiKey") + + // verify updated Pet + val exception = shouldThrow { + api.getPetById(petId) + } + exception.message?.shouldContain("Pet not found") + } + + } + +} diff --git a/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 index 7e93b07545d..eebc0a22260 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 @@ -59,11 +59,11 @@ function Initialize-PSPet { 'Creating PSCustomObject: PSPetstore => PSPet' | Write-Debug $PSBoundParameters | Out-DebugParameter | Write-Debug - if (!$Name) { + if ($Name -eq $null) { throw "invalid value for 'Name', 'Name' cannot be null." } - if (!$PhotoUrls) { + if ($PhotoUrls -eq $null) { throw "invalid value for 'PhotoUrls', 'PhotoUrls' cannot be null." } @@ -120,17 +120,17 @@ function ConvertFrom-PSJsonToPet { } If ([string]::IsNullOrEmpty($Json) -or $Json -eq "{}") { # empty json - throw "Error! Empty JSON cannot be serialized due to the required property `name` missing." + throw "Error! Empty JSON cannot be serialized due to the required property 'name' missing." } if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { - throw "Error! JSON cannot be serialized due to the required property `name` missing." + throw "Error! JSON cannot be serialized due to the required property 'name' missing." } else { $Name = $JsonParameters.PSobject.Properties["name"].value } if (!([bool]($JsonParameters.PSobject.Properties.name -match "photoUrls"))) { - throw "Error! JSON cannot be serialized due to the required property `photoUrls` missing." + throw "Error! JSON cannot be serialized due to the required property 'photoUrls' missing." } else { $PhotoUrls = $JsonParameters.PSobject.Properties["photoUrls"].value } diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb index 08a0c17e26f..6bb453bf498 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb @@ -313,7 +313,7 @@ module Petstore case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] - else fail ArgumentError, 'Authentication token must be in `query` of `header`' + else fail ArgumentError, 'Authentication token must be in `query` or `header`' end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb index c6bfe01bfd4..fcbeed5b110 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb @@ -192,11 +192,13 @@ module Petstore # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth - def api_key_with_prefix(param_name) + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + "#{@api_key_prefix[param_name]} #{key}" else - @api_key[param_name] + key end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 9ced3731a30..bc82c400eac 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -308,7 +308,7 @@ module Petstore case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] - else fail ArgumentError, 'Authentication token must be in `query` of `header`' + else fail ArgumentError, 'Authentication token must be in `query` or `header`' end end end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 1552912eb8a..2769fdb2998 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -197,11 +197,13 @@ module Petstore # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth - def api_key_with_prefix(param_name) + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + "#{@api_key_prefix[param_name]} #{key}" else - @api_key[param_name] + key end end diff --git a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 224d1fc911b..6ee033b07f3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,18 +18,16 @@ open class RequestBuilder { var credential: URLCredential? 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) -> 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5bbf323f820..24b0015a270 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 134d6aea416..58c4b8a093c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 48cfe7187b9..fb3bb8ce00a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index c938db72004..5cd3629127b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8a83eda39a..95adcc200ae 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 505ed1b0c5c..cfd30068a9d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index 368b4edffb9..9685c32b69e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -21,8 +21,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -39,7 +39,20 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to custom request constructor. */ open func createURLRequest() -> URLRequest? { - let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + encoding = JSONDataEncoding() + } + guard let originalRequest = try? URLRequest(url: URLString, method: HTTPMethod(rawValue: method)!, headers: buildHeaders()) else { return nil } return try? encoding.encode(originalRequest, with: parameters) } @@ -64,56 +77,73 @@ open class AlamofireRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let managerId: String = UUID().uuidString + let managerId = 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() + guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } - let xMethod = Alamofire.HTTPMethod(rawValue: method) - let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } - .map { $0.0 } + let encoding: ParameterEncoding? - if fileKeys.count > 0 { - manager.upload(multipartFormData: { mpForm in - for (k, v) in self.parameters! { - switch v { - case let fileURL as URL: - if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { - mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } else { - mpForm.append(fileURL, withName: k) + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = nil + + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } else { + mpForm.append(fileURL, withName: k) + } + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + default: + fatalError("Unprocessable value \(v) with key \(k)") } - case let string as String: - mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) - case let number as NSNumber: - mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) - default: - fatalError("Unprocessable value \(v) with key \(k)") } - } - }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in - switch encodingResult { - case .success(let upload, _, _): - if let onProgressReady = self.onProgressReady { - onProgressReady(upload.uploadProgress) + }, to: URLString, method: xMethod, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, apiResponseQueue, completion) + case .failure(let encodingError): + apiResponseQueue.async { + completion(.failure(ErrorResponse.error(415, nil, nil, encodingError))) + } } - self.processRequest(request: upload, managerId, apiResponseQueue, completion) - case .failure(let encodingError): - apiResponseQueue.async { - completion(.failure(ErrorResponse.error(415, nil, encodingError))) - } - } - }) - } else { - let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + }) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = URLEncoding(destination: .httpBody) + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + + if let encoding = encoding { + let request = makeRequest(manager: manager, method: xMethod, encoding: encoding, headers: headers) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } processRequest(request: request, managerId, apiResponseQueue, completion) } - } fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { @@ -136,7 +166,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let .success(value): completion(.success(Response(response: stringResponse.response!, body: value as? T))) case let .failure(error): - completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, error))) + completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) } }) @@ -178,9 +208,9 @@ open class AlamofireRequestBuilder: RequestBuilder { completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, dataResponse.data, requestParserError))) + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, dataResponse.data, error))) + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) } return }) @@ -192,7 +222,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case .success: completion(.success(Response(response: voidResponse.response!, body: nil))) case let .failure(error): - completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, error))) + completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } }) @@ -204,7 +234,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case .success: completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, error))) + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) } }) @@ -294,7 +324,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild case let .success(value): completion(.success(Response(response: stringResponse.response!, body: value as? T))) case let .failure(error): - completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, error))) + completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) } }) @@ -306,7 +336,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild case .success: completion(.success(Response(response: voidResponse.response!, body: nil))) case let .failure(error): - completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, error))) + completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } }) @@ -318,7 +348,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild case .success: completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, error))) + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) } }) @@ -327,17 +357,17 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild cleanupRequest() guard dataResponse.result.isSuccess else { - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!))) + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, dataResponse.result.error!))) return } guard let data = dataResponse.data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(-1, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(-1, nil, dataResponse.response, DecodableRequestBuilderError.emptyDataResponse))) return } guard let httpResponse = dataResponse.response else { - completion(.failure(ErrorResponse.error(-2, nil, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, nil, dataResponse.response, DecodableRequestBuilderError.nilHTTPResponse))) return } @@ -347,7 +377,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, httpResponse, error))) } }) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock index 5ded1f78890..30f84a6b9c3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock @@ -20,4 +20,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c -COCOAPODS: 1.9.0 +COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index c9ad0385970..901182fb107 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -7,8 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */; }; 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -17,9 +17,10 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + A5465873259E306E00C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */; }; A5EA12542419387200E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12522419387100E30FC3 /* FileUtils.swift */; }; A5EA12552419387200E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12532419387100E30FC3 /* UIImage+Extras.swift */; }; - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; + B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -33,8 +34,8 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; + 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -47,14 +48,15 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12522419387100E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12532419387100E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -62,7 +64,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */, + B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -70,30 +72,19 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */, + 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 203D4495376E4EB72474B091 /* Pods */ = { - isa = PBXGroup; - children = ( - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */, - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */, - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */, - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */, - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */, + 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */, + D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -105,7 +96,7 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 203D4495376E4EB72474B091 /* Pods */, + AC485EA5DC51CA28F3F7FECF /* Pods */, ); sourceTree = ""; }; @@ -123,6 +114,7 @@ children = ( 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */, 6D4EFB961C692C6300B96B06 /* ViewController.swift */, + A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */, 6D4EFB981C692C6300B96B06 /* Main.storyboard */, 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */, 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */, @@ -145,6 +137,18 @@ path = SwaggerClientTests; sourceTree = ""; }; + AC485EA5DC51CA28F3F7FECF /* Pods */ = { + isa = PBXGroup; + children = ( + 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */, + FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */, + 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */, + 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -152,11 +156,11 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */, + 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */, + 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -171,7 +175,7 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */, + 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -247,7 +251,27 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */ = { + 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", + "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -269,7 +293,7 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */ = { + 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -291,26 +315,6 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -319,6 +323,7 @@ buildActionMask = 2147483647; files = ( 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */, + A5465873259E306E00C3929B /* BearerDecodableRequestBuilder.swift in Sources */, 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -476,7 +481,7 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */; + baseConfigurationReference = 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; @@ -489,7 +494,7 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */; + baseConfigurationReference = FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; @@ -502,7 +507,7 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */; + baseConfigurationReference = 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; @@ -516,7 +521,7 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */; + baseConfigurationReference = 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift index b1896774c73..b89c28a3ca7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift @@ -7,6 +7,7 @@ // import UIKit +import PetstoreClient @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -15,6 +16,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. + + // Customize requestBuilderFactory + PetstoreClientAPI.requestBuilderFactory = BearerRequestBuilderFactory() + return true } diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift new file mode 100644 index 00000000000..f71480b0bd5 --- /dev/null +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift @@ -0,0 +1,79 @@ +// +// BearerDecodableRequestBuilder.swift +// SwaggerClient +// +// Created by Bruno Coelho on 31/12/2020. +// Copyright © 2020 Swagger. All rights reserved. +// + +import Foundation +import Alamofire +import PetstoreClient + +class BearerRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + BearerRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + BearerDecodableRequestBuilder.self + } +} + +class BearerRequestBuilder: AlamofireRequestBuilder { + override func createSessionManager() -> SessionManager { + let sessionManager = super.createSessionManager() + + let bearerTokenHandler = BearerTokenHandler() + sessionManager.adapter = bearerTokenHandler + sessionManager.retrier = bearerTokenHandler + + return sessionManager + } +} + +class BearerDecodableRequestBuilder: AlamofireDecodableRequestBuilder { + override func createSessionManager() -> SessionManager { + let sessionManager = super.createSessionManager() + + let bearerTokenHandler = BearerTokenHandler() + sessionManager.adapter = bearerTokenHandler + sessionManager.retrier = bearerTokenHandler + + return sessionManager + } +} + +class BearerTokenHandler: RequestAdapter, RequestRetrier { + private static var bearerToken: String? = nil + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + if let bearerToken = Self.bearerToken { + var urlRequest = urlRequest + urlRequest.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization") + return urlRequest + } + + return urlRequest + } + + func should(_: SessionManager, retry request: Request, with _: Error, completion: @escaping RequestRetryCompletion) { + if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { + Self.startRefreshingToken { isTokenRefreshed in + completion(isTokenRefreshed, 0.0) + } + } else { + completion(false, 0.0) + } + } + + private static func startRefreshingToken(completionHandler: @escaping (Bool) -> Void) { + // Get a bearer token + let dummyBearerToken = "..." + + bearerToken = dummyBearerToken + PetstoreClientAPI.customHeaders["Authorization"] = "Bearer \(dummyBearerToken)" + + completionHandler(true) + } +} diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/alamofireLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/MapTest.md b/samples/client/petstore/swift5/alamofireLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/alamofireLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/alamofireLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/alamofireLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/alamofireLibrary/project.yml b/samples/client/petstore/swift5/alamofireLibrary/project.yml index 148b42517be..08035907b99 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/project.yml +++ b/samples/client/petstore/swift5/alamofireLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 65a513f941e..f846096ae63 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -44,9 +44,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 03f9b6cbde6..34fa51403b6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -42,9 +42,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -80,9 +86,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -118,9 +130,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -156,9 +174,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -194,9 +218,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -233,12 +263,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -276,9 +312,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -355,7 +397,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -363,9 +405,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -482,7 +530,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -493,17 +541,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -554,17 +605,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -601,9 +654,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -640,7 +699,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -648,9 +707,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 1b47d1a5dbc..f6b896887ef 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -47,9 +47,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 8e41c18d161..01b5812ecf3 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -46,9 +46,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -92,14 +98,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -149,12 +157,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -197,12 +211,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -246,9 +266,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -288,9 +314,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -335,7 +367,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -343,9 +375,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -390,7 +428,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -398,9 +436,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -445,7 +489,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -453,9 +497,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 259a7cf6ada..c3499823631 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -47,16 +47,22 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Returns pet inventories by status - parameter apiResponseQueue: The queue on which api response is dispatched. - - returns: AnyPublisher<[String:Int], Error> + - returns: AnyPublisher<[String: Int], Error> */ @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[String: Int], Error> { @@ -79,7 +85,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -88,9 +94,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -131,9 +143,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -170,9 +188,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 747e2f31fb9..9df08496cc2 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -44,9 +44,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -83,9 +89,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -122,9 +134,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -165,9 +183,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -207,9 +231,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -250,12 +280,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -290,9 +326,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -335,9 +377,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/combineLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/combineLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/combineLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/combineLibrary/docs/MapTest.md b/samples/client/petstore/swift5/combineLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/combineLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/combineLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/combineLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/combineLibrary/project.yml b/samples/client/petstore/swift5/combineLibrary/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/combineLibrary/project.yml +++ b/samples/client/petstore/swift5/combineLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/default/.openapi-generator/VERSION b/samples/client/petstore/swift5/default/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5bbf323f820..24b0015a270 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 134d6aea416..58c4b8a093c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 48cfe7187b9..fb3bb8ce00a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index c938db72004..5cd3629127b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8a83eda39a..95adcc200ae 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 505ed1b0c5c..cfd30068a9d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/default/docs/FakeAPI.md b/samples/client/petstore/swift5/default/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/default/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/default/docs/MapTest.md b/samples/client/petstore/swift5/default/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/default/docs/MapTest.md +++ b/samples/client/petstore/swift5/default/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/default/docs/StoreAPI.md b/samples/client/petstore/swift5/default/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/default/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/default/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/default/project.yml b/samples/client/petstore/swift5/default/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/default/project.yml +++ b/samples/client/petstore/swift5/default/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES b/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES index 4959a60cde9..b78ea60c112 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES @@ -15,8 +15,6 @@ PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift PetstoreClient/Classes/OpenAPIs/Models.swift PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift PetstoreClient/Classes/OpenAPIs/Models/Category.swift -PetstoreClient/Classes/OpenAPIs/Models/InlineObject.swift -PetstoreClient/Classes/OpenAPIs/Models/InlineObject1.swift PetstoreClient/Classes/OpenAPIs/Models/Order.swift PetstoreClient/Classes/OpenAPIs/Models/Pet.swift PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -27,8 +25,6 @@ PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift README.md docs/ApiResponse.md docs/Category.md -docs/InlineObject.md -docs/InlineObject1.md docs/Order.md docs/Pet.md docs/PetAPI.md diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift index 74babd69f97..71c2a2fa5b7 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 06a266aab47..f46c7ac57ea 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index ff110015954..c34e8332551 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 04a9b99643c..255ffb0cb55 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -43,9 +43,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -82,9 +88,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -164,9 +182,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -203,9 +227,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -243,12 +273,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -283,9 +319,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -328,9 +370,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index cb69946cd9f..2980550e3cb 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -18,7 +18,6 @@ public struct Pet: Codable { public var id: Int64? public var category: Category? public var name: String? - @available(*, deprecated, message: "This property is deprecated.") public var photoUrls: [String] public var tags: [Tag]? diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/deprecated/README.md b/samples/client/petstore/swift5/deprecated/README.md index 62088c981e2..619c4036f44 100644 --- a/samples/client/petstore/swift5/deprecated/README.md +++ b/samples/client/petstore/swift5/deprecated/README.md @@ -51,8 +51,6 @@ Class | Method | HTTP request | Description - [ApiResponse](docs/ApiResponse.md) - [Category](docs/Category.md) - - [InlineObject](docs/InlineObject.md) - - [InlineObject1](docs/InlineObject1.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) - [Tag](docs/Tag.md) diff --git a/samples/client/petstore/swift5/deprecated/docs/StoreAPI.md b/samples/client/petstore/swift5/deprecated/docs/StoreAPI.md index 4c04b6e431f..f28f141f638 100644 --- a/samples/client/petstore/swift5/deprecated/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/deprecated/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/deprecated/project.yml b/samples/client/petstore/swift5/deprecated/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/deprecated/project.yml +++ b/samples/client/petstore/swift5/deprecated/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 1a1716eb8a3..ddd555e5daa 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ internal struct APIHelper { internal static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ internal struct APIHelper { internal static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ internal struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift index 5dfbd9cea8d..f5569a9fdf3 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ internal class RequestBuilder { var credential: URLCredential? var headers: [String: String] internal let parameters: [String: Any]? - internal let isBody: Bool internal let method: String internal let URLString: String @@ -27,11 +26,10 @@ internal class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 174e6c12aed..537dacc4c1a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ internal class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index ab1b8f09247..03fd8a8ca15 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ internal class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ internal class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ internal class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ internal class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ internal class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ internal class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ internal class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 548c5fb3523..76f1b99ed1c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ internal class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index cb54fce0dcb..658ef61ddc0 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ internal class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ internal class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ internal class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ internal class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ internal class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ internal class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ internal class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index f1e423111d0..3f0f902ccd8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ internal class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ internal class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ internal class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ internal class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ internal class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ internal class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index c8d714e8991..f4a787ff486 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ internal class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ internal class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 6089ac67d0d..f372f83aac8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } internal enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } internal enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 81fd6dcc6e8..3b4f6c149fa 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -internal struct Category: Codable { +internal struct Category: Codable, Hashable { internal var id: Int64? internal var name: String = "default-name" diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 9ef32df964c..8b4501e67aa 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -internal struct Tag: Codable { +internal struct Tag: Codable, Hashable { internal var id: Int64? internal var name: String? diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a165d52ff06..11378e5653f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() internal class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ internal class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") internal var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required internal init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ internal class URLSessionRequestBuilder: RequestBuilder { } override internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ internal class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ internal class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/nonPublicApi/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md index dd2d871bca8..b7dbe0b2260 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - internal class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + internal class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/MapTest.md b/samples/client/petstore/swift5/nonPublicApi/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/MapTest.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/nonPublicApi/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/nonPublicApi/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/nonPublicApi/docs/StoreAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/StoreAPI.md index cec8acecb81..02968503f82 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - internal class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + internal class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/nonPublicApi/project.yml b/samples/client/petstore/swift5/nonPublicApi/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/project.yml +++ b/samples/client/petstore/swift5/nonPublicApi/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 2e9ad96a66b..e1c068f2627 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class AnotherFakeAPI: NSObject { +@objc open class AnotherFakeAPI : NSObject { /** To test special tags @@ -40,9 +40,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 6483ab29bcc..0af3b8d55a8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class FakeAPI: NSObject { +@objc open class FakeAPI : NSObject { /** - parameter body: (body) Input boolean as post body (optional) @@ -38,9 +38,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ import Foundation var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ import Foundation "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ import Foundation let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ import Foundation "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ import Foundation "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ import Foundation let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index b9cfc75eeb4..7115a294b03 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class FakeClassnameTags123API: NSObject { +@objc open class FakeClassnameTags123API : NSObject { /** To test class name in snake case @@ -43,9 +43,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index d022b687736..7dc0f6ecde4 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class PetAPI: NSObject { +@objc open class PetAPI : NSObject { /** Add a new pet to the store @@ -42,9 +42,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ import Foundation let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ import Foundation var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ import Foundation var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ import Foundation let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ import Foundation let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ import Foundation let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a19d12c7d24..2abb82081dd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class StoreAPI: NSObject { +@objc open class StoreAPI : NSObject { /** Delete purchase order by ID @@ -43,9 +43,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ import Foundation - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 4dfe4da1a02..1b384965e07 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,7 +7,7 @@ import Foundation -@objc open class UserAPI: NSObject { +@objc open class UserAPI : NSObject { /** Create user @@ -40,9 +40,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ import Foundation var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ import Foundation let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 0e034abbf72..a69d5c26afd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -@objc public class Category: NSObject, Codable { +@objc public class Category: NSObject, Codable, Hashable { public var _id: Int64? public var _idNum: NSNumber? { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index fc02765d30e..d3aefb0946c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -@objc public class Tag: NSObject, Codable { +@objc public class Tag: NSObject, Codable, Hashable { public var _id: Int64? public var _idNum: NSNumber? { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/objcCompatible/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/objcCompatible/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md index f7faf3aa2aa..a5a97eb2aeb 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/objcCompatible/docs/MapTest.md b/samples/client/petstore/swift5/objcCompatible/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/MapTest.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/objcCompatible/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/objcCompatible/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/objcCompatible/docs/StoreAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/StoreAPI.md index ba59be9d543..4add349c9c1 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/objcCompatible/project.yml b/samples/client/petstore/swift5/objcCompatible/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/objcCompatible/project.yml +++ b/samples/client/petstore/swift5/objcCompatible/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/promisekitLibrary/Cartfile b/samples/client/petstore/swift5/promisekitLibrary/Cartfile index 01fd3663de5..9a00bb83e5b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Cartfile +++ b/samples/client/petstore/swift5/promisekitLibrary/Cartfile @@ -1,2 +1,2 @@ -github "mxcl/PromiseKit" ~> 6.12.0 +github "mxcl/PromiseKit" ~> 6.13.1 diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec index ef330727bff..92e54fcfeb7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'PromiseKit/CorePromise', '~> 6.12.0' + s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' end diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index c3a97ff074c..84159541989 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -43,9 +43,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 80153ba634d..b87b809198b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -41,9 +41,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -78,9 +84,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -115,9 +127,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -189,9 +213,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -201,7 +231,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -227,12 +257,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +305,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -294,7 +336,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - 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, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> 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, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> 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(apiResponseQueue) { result -> Void in switch result { @@ -347,7 +389,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -355,9 +397,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -441,7 +489,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - 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, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> 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, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -473,7 +521,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -484,17 +532,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -509,7 +560,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -544,17 +595,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -590,9 +643,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -628,7 +687,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -636,9 +695,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 3a05f8eaf60..6066f4ec831 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -46,9 +46,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 18d3fd1d094..e60028960c8 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -45,9 +45,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +64,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -90,14 +96,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -146,12 +154,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -193,12 +207,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -241,9 +261,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -282,9 +308,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -296,7 +328,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -328,7 +360,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -336,9 +368,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -350,7 +388,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -382,7 +420,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -390,9 +428,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -404,7 +448,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -436,7 +480,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -444,9 +488,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 20fc8a1468c..a76e39ab8f0 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -46,16 +46,22 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Returns pet inventories by status - parameter apiResponseQueue: The queue on which api response is dispatched. - - returns: Promise<[String:Int]> + - returns: Promise<[String: Int]> */ open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[String: Int]> { let deferred = Promise<[String: Int]>.pending() @@ -77,7 +83,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -86,9 +92,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -128,9 +140,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -166,9 +184,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 89c48c3b28f..b451a340454 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -43,9 +43,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -81,9 +87,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,9 +131,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -161,9 +179,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -202,9 +226,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -215,7 +245,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -244,12 +274,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -283,9 +319,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -296,7 +338,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -327,9 +369,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock index 9e4fdf68367..c75f76b2fb8 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock @@ -1,7 +1,7 @@ PODS: - PetstoreClient (1.0.0): - - PromiseKit/CorePromise (~> 6.12.0) - - PromiseKit/CorePromise (6.12.0) + - PromiseKit/CorePromise (~> 6.13.1) + - PromiseKit/CorePromise (6.13.1) DEPENDENCIES: - PetstoreClient (from `../`) @@ -15,9 +15,9 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - PetstoreClient: 97929409c1dd42edb2cf067b2cc182434d87f1aa - PromiseKit: c06835ba442ce5454ce3cdde470232804a6e4ff8 + PetstoreClient: bf095c434cf89014d1b574779fcc7701a551fcce + PromiseKit: 28fda91c973cc377875d8c0ea4f973013c05b6db PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c -COCOAPODS: 1.9.0 +COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/promisekitLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md index 5519037c52c..72d6935fb92 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md @@ -534,7 +534,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties( param: [String:String]) -> Promise + open class func testInlineAdditionalProperties( param: [String: String]) -> Promise ``` test inline additionalProperties @@ -544,7 +544,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param).then { @@ -560,7 +560,7 @@ FakeAPI.testInlineAdditionalProperties(param: param).then { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/MapTest.md b/samples/client/petstore/swift5/promisekitLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/promisekitLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/promisekitLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/promisekitLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/StoreAPI.md index 085d479bce2..e33defdf28d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/StoreAPI.md @@ -59,7 +59,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory() -> Promise<[String:Int]> + open class func getInventory() -> Promise<[String: Int]> ``` Returns pet inventories by status @@ -87,7 +87,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/promisekitLibrary/project.yml b/samples/client/petstore/swift5/promisekitLibrary/project.yml index 3f6d4d9253e..d6d2be8a224 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/project.yml +++ b/samples/client/petstore/swift5/promisekitLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5bbf323f820..24b0015a270 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 134d6aea416..58c4b8a093c 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 48cfe7187b9..fb3bb8ce00a 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index c938db72004..5cd3629127b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8a83eda39a..95adcc200ae 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 505ed1b0c5c..cfd30068a9d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index e00b87b4acc..4089925077f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public private(set) var id: Int64? public private(set) var name: String = "default-name" diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 08c29fb3f36..c35e07111a0 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public private(set) var id: Int64? public private(set) var name: String? diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/readonlyProperties/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/readonlyProperties/docs/FakeAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/MapTest.md b/samples/client/petstore/swift5/readonlyProperties/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/MapTest.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/readonlyProperties/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/readonlyProperties/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/readonlyProperties/docs/StoreAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/readonlyProperties/project.yml b/samples/client/petstore/swift5/readonlyProperties/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/readonlyProperties/project.yml +++ b/samples/client/petstore/swift5/readonlyProperties/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 001f7160811..1c777abff63 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 1289d6e2a94..642370b2bc1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index f54d6e7fcf0..4cf17d8a884 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 92893a31295..fd4c8fb152a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 5024c9dc8f6..a50d54cada1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index c96c572b50c..58b6b51d8b0 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/resultLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/resultLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/resultLibrary/docs/MapTest.md b/samples/client/petstore/swift5/resultLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/resultLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/resultLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/resultLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/resultLibrary/project.yml b/samples/client/petstore/swift5/resultLibrary/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/resultLibrary/project.yml +++ b/samples/client/petstore/swift5/resultLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile index 72cbede9599..37dea8f2ead 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile +++ b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile @@ -1,2 +1,2 @@ -github "ReactiveX/RxSwift" ~> 5.0.1 +github "ReactiveX/RxSwift" ~> 5.1.1 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec index 76ab70698e0..2e94d8a71f3 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'RxSwift', '~> 5.0.0' + s.dependency 'RxSwift', '~> 5.1.1' end diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 792371b3842..1affe07267f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -45,9 +45,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 3e9b32438c8..f76577526ec 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -43,9 +43,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -82,9 +88,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -160,9 +178,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -199,9 +223,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -239,12 +269,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -283,9 +319,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -363,7 +405,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -371,9 +413,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -491,7 +539,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -502,17 +550,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -564,17 +615,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -612,9 +665,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -652,7 +711,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -660,9 +719,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 989a914f379..ec0775dbde0 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -48,9 +48,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index b3a26902360..e1152e64add 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -47,9 +47,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -94,14 +100,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,12 +160,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -201,12 +215,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -251,9 +271,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -294,9 +320,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -342,7 +374,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -350,9 +382,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -398,7 +436,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -406,9 +444,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +498,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -462,9 +506,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index dea3933433c..4dac29ad2be 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -48,16 +48,22 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Returns pet inventories by status - parameter apiResponseQueue: The queue on which api response is dispatched. - - returns: Observable<[String:Int]> + - returns: Observable<[String: Int]> */ open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[String: Int]> { return Observable.create { observer -> Disposable in @@ -81,7 +87,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -90,9 +96,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -134,9 +146,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -174,9 +192,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 3447ea28c0e..5bfcc43e2a2 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -45,9 +45,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,9 +91,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -125,9 +137,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,9 +187,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -212,9 +236,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -256,12 +286,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -297,9 +333,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -343,9 +385,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock index 843ccc1723e..be3757ec1f4 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock @@ -1,7 +1,7 @@ PODS: - PetstoreClient (1.0.0): - - RxSwift (~> 5.0.0) - - RxSwift (5.0.1) + - RxSwift (~> 5.1.1) + - RxSwift (5.1.1) DEPENDENCIES: - PetstoreClient (from `../`) @@ -15,9 +15,9 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - PetstoreClient: ca66372305d63921e72f65b3de84aeb705eba5a1 - RxSwift: e2dc62b366a3adf6a0be44ba9f405efd4c94e0c4 + PetstoreClient: f3d073d9543d90440a155feec649c16b98d84c31 + RxSwift: 81470a2074fa8780320ea5fe4102807cb7118178 PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c -COCOAPODS: 1.9.0 +COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md index aae8b34423b..0f616c1db2d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md @@ -470,7 +470,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String]) -> Observable + open class func testInlineAdditionalProperties(param: [String: String]) -> Observable ``` test inline additionalProperties @@ -480,7 +480,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new ``` @@ -489,7 +489,7 @@ let param = "TODO" // [String:String] | request body Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/MapTest.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/rxswiftLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/rxswiftLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/StoreAPI.md index a648ce8859b..456d08d952a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/StoreAPI.md @@ -52,7 +52,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory() -> Observable<[String:Int]> + open class func getInventory() -> Observable<[String: Int]> ``` Returns pet inventories by status @@ -73,7 +73,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/rxswiftLibrary/project.yml b/samples/client/petstore/swift5/rxswiftLibrary/project.yml index 667956cb12a..60393c28e66 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/project.yml +++ b/samples/client/petstore/swift5/rxswiftLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION index d99e7162d01..3fa3b389a57 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5b09f955711..1f7f2ffbe17 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? [Any?] { - 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)" } @@ -47,7 +47,7 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + return collection.filter { $0 != nil }.map {"\($0!)"}.joined(separator: ",") } return source } @@ -55,7 +55,7 @@ public struct APIHelper { 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? [Any?] { - collection.filter({ $0 != nil }).map({"\($0!)"}).forEach { value in + collection.filter { $0 != nil }.map {"\($0!)"}.forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } } else if let value = item.value { diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index a5c2d605dff..3183a307a7b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -18,7 +18,6 @@ open class RequestBuilder { var credential: URLCredential? var headers: [String: String] public let parameters: [String: Any]? - public let isBody: Bool public let method: String public let URLString: String @@ -27,11 +26,10 @@ open class RequestBuilder { /// If you need to get the request's progress in older OS versions, please use Alamofire http client. 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]?, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters - self.isBody = isBody self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5bbf323f820..24b0015a270 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -40,9 +40,15 @@ open class AnotherFakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 134d6aea416..58c4b8a093c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -38,9 +38,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -73,9 +79,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -108,9 +120,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -143,9 +161,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,9 +202,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -214,12 +244,18 @@ open class FakeAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON() + "query": query.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -254,9 +290,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -330,7 +372,7 @@ open class FakeAPI { "date": date?.encodeToJSON(), "dateTime": dateTime?.encodeToJSON(), "password": password?.encodeToJSON(), - "callback": callback?.encodeToJSON() + "callback": callback?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -338,9 +380,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -454,7 +502,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), - "enum_form_string": enumFormString?.encodeToJSON() + "enum_form_string": enumFormString?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -465,17 +513,20 @@ open class FakeAPI { "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON() + "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), - "enum_header_string": enumHeaderString?.encodeToJSON() + "enum_header_string": enumHeaderString?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -523,17 +574,19 @@ open class FakeAPI { "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON() + "int64_group": int64Group?.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), - "boolean_group": booleanGroup?.encodeToJSON() + "boolean_group": booleanGroup?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -567,9 +620,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -603,7 +662,7 @@ open class FakeAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), - "param2": param2.encodeToJSON() + "param2": param2.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -611,9 +670,15 @@ open class FakeAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 48cfe7187b9..fb3bb8ce00a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -43,9 +43,15 @@ open class FakeClassnameTags123API { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index c938db72004..5cd3629127b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -42,9 +42,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -85,14 +91,16 @@ open class PetAPI { let parameters: [String: Any]? = nil let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ - "api_key": apiKey?.encodeToJSON() + "api_key": apiKey?.encodeToJSON(), ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -139,12 +147,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON() + "status": status.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -184,12 +198,18 @@ open class PetAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON() + "tags": tags.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -230,9 +250,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -269,9 +295,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -313,7 +345,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), - "status": status?.encodeToJSON() + "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -321,9 +353,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -365,7 +403,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "file": file?.encodeToJSON() + "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -373,9 +411,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -417,7 +461,7 @@ open class PetAPI { let URLString = PetstoreClientAPI.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), - "requiredFile": requiredFile.encodeToJSON() + "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) @@ -425,9 +469,15 @@ open class PetAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8a83eda39a..95adcc200ae 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -43,9 +43,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -72,7 +78,7 @@ open class StoreAPI { - API Key: - type: apiKey api_key - name: api_key - - returns: RequestBuilder<[String:Int]> + - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" @@ -81,9 +87,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -121,9 +133,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,9 +175,15 @@ open class StoreAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 505ed1b0c5c..cfd30068a9d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -40,9 +40,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -76,9 +82,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -112,9 +124,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -152,9 +170,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -191,9 +215,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,12 +261,18 @@ open class UserAPI { var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), - "password": password.encodeToJSON() + "password": password.encodeToJSON(), ]) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,9 +304,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -310,9 +352,15 @@ open class UserAPI { let url = URLComponents(string: URLString) + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index c0542c14c08..96e26a20f7d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -11,7 +11,7 @@ protocol JSONEncodable { } public enum ErrorResponse: Error { - case error(Int, Data?, Error) + case error(Int, Data?, URLResponse?, Error) } public enum DownloadException: Error { diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index faf66b272a4..6a19bb02d0d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,7 @@ import Foundation -public struct Category: Codable { +public struct Category: Codable, Hashable { public var id: Int64? public var name: String = "default-name" diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 82c02f04b69..8b8e24fc39c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,7 @@ import Foundation -public struct Tag: Codable { +public struct Tag: Codable, Hashable { public var id: Int64? public var name: String? diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 8bbaba9b4d9..28bc756aa58 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -24,12 +24,6 @@ private var urlSessionStore = SynchronizedDictionary() open class URLSessionRequestBuilder: RequestBuilder { - private var observation: NSKeyValueObservation? - - deinit { - observation?.invalidate() - } - // swiftlint:disable:next weak_delegate fileprivate let sessionDelegate = SessionDelegate() @@ -44,10 +38,11 @@ open class URLSessionRequestBuilder: RequestBuilder { - intercept and handle errors like authorization - retry the request. */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - 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) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) } /** @@ -101,32 +96,37 @@ open class URLSessionRequestBuilder: RequestBuilder { } override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { - let urlSessionId: String = UUID().uuidString + let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession - let parameters: [String: Any] = self.parameters ?? [:] - - let fileKeys = parameters.filter { $1 is URL } - .map { $0.0 } - - let encoding: ParameterEncoding - if fileKeys.count > 0 { - encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) - } else if isBody { - encoding = JSONDataEncoding() - } else { - encoding = URLEncoding() - } - guard let xMethod = HTTPMethod(rawValue: method) else { fatalError("Unsuported Http method - \(method)") } + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + let cleanupRequest = { urlSessionStore[urlSessionId] = nil - self.observation?.invalidate() } do { @@ -167,26 +167,25 @@ open class URLSessionRequestBuilder: RequestBuilder { } catch { apiResponseQueue.async { cleanupRequest() - completion(.failure(ErrorResponse.error(415, nil, error))) + completion(.failure(ErrorResponse.error(415, nil, nil, error))) } } - } fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -227,9 +226,9 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: filePath as? T))) } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, requestParserError))) + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) } catch let error { - completion(.failure(ErrorResponse.error(400, data, error))) + completion(.failure(ErrorResponse.error(400, data, response, error))) } case is Void.Type: @@ -311,17 +310,17 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { if let error = error { - completion(.failure(ErrorResponse.error(-1, data, error))) + completion(.failure(ErrorResponse.error(-1, data, response, error))) return } guard let httpResponse = response as? HTTPURLResponse else { - completion(.failure(ErrorResponse.error(-2, data, DecodableRequestBuilderError.nilHTTPResponse))) + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) return } guard httpResponse.isStatusCodeSuccessful else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) return } @@ -343,7 +342,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) return } @@ -353,7 +352,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case let .success(decodableObj): completion(.success(Response(response: httpResponse, body: decodableObj))) case let .failure(error): - completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error))) + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) } } } @@ -425,7 +424,7 @@ private class URLEncoding: ParameterEncoding { } } -private class FileUploadEncoding: ParameterEncoding { +private class FormDataEncoding: ParameterEncoding { let contentTypeForFormPart: (_ fileURL: URL) -> String? @@ -569,7 +568,25 @@ private class FileUploadEncoding: ParameterEncoding { } -fileprivate extension Data { +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { /// Append string to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. @@ -583,7 +600,7 @@ fileprivate extension Data { } } -fileprivate extension Optional where Wrapped == Data { +private extension Optional where Wrapped == Data { var orEmpty: Data { self ?? Data() } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index f3d009d59af..9c371f929db 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + A5465867259E09C600C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */; }; A5EA12642419439700E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12622419439700E30FC3 /* FileUtils.swift */; }; A5EA12652419439700E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12632419439700E30FC3 /* UIImage+Extras.swift */; }; FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; @@ -49,6 +50,7 @@ 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12622419439700E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12632419439700E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; @@ -123,6 +125,7 @@ children = ( 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */, 6D4EFB961C692C6300B96B06 /* ViewController.swift */, + A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */, 6D4EFB981C692C6300B96B06 /* Main.storyboard */, 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */, 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */, @@ -317,6 +320,7 @@ buildActionMask = 2147483647; files = ( 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */, + A5465867259E09C600C3929B /* BearerDecodableRequestBuilder.swift in Sources */, 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift index b1896774c73..b89c28a3ca7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/AppDelegate.swift @@ -7,6 +7,7 @@ // import UIKit +import PetstoreClient @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -15,6 +16,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. + + // Customize requestBuilderFactory + PetstoreClientAPI.requestBuilderFactory = BearerRequestBuilderFactory() + return true } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift new file mode 100644 index 00000000000..a28a4c90c0e --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift @@ -0,0 +1,144 @@ +// +// BearerDecodableRequestBuilder.swift +// SwaggerClient +// +// Created by Bruno Coelho on 31/12/2020. +// Copyright © 2020 Swagger. All rights reserved. +// + +import Foundation +import PetstoreClient + +class BearerRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + BearerRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + BearerDecodableRequestBuilder.self + } +} + +class BearerRequestBuilder: URLSessionRequestBuilder { + override func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (Result, Error>) -> Void) { + + // Before making the request, we can validate if we have a bearer token to be able to make a request + BearerTokenHandler.refreshTokenIfDoesntExist { + + // Here we make the request + super.execute(apiResponseQueue) { result in + + switch result { + case .success: + // If we got a successful response, we send the response to the completion block + completion(result) + + case let .failure(error): + + // If we got a failure response, we will analyse the error to see what we should do with it + if case let ErrorResponse.error(_, data, response, error) = error { + + // If the error is an ErrorResponse.error() we will analyse it to see if it's a 401, and if it's a 401, we will refresh the token and retry the request + BearerTokenHandler.refreshTokenIfUnauthorizedRequestResponse( + data: data, + response: response, + error: error + ) { wasTokenRefreshed in + + if wasTokenRefreshed { + // If the token was refreshed, it's because it was a 401 error, so we refreshed the token, and we are going to retry the request by calling self.execute() + self.execute(apiResponseQueue, completion) + } else { + // If the token was not refreshed, it's because it was not a 401 error, so we send the response to the completion block + completion(result) + } + } + } else { + // If it's an unknown error, we send the response to the completion block + completion(result) + } + + } + } + } + } +} + +class BearerDecodableRequestBuilder: URLSessionDecodableRequestBuilder { + override func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (Result, Error>) -> Void) { + + // Before making the request, we can validate if we have a bearer token to be able to make a request + BearerTokenHandler.refreshTokenIfDoesntExist { + + // Here we make the request + super.execute(apiResponseQueue) { result in + + switch result { + case .success: + // If we got a successful response, we send the response to the completion block + completion(result) + + case let .failure(error): + + // If we got a failure response, we will analyse the error to see what we should do with it + if case let ErrorResponse.error(_, data, response, error) = error { + + // If the error is an ErrorResponse.error() we will analyse it to see if it's a 401, and if it's a 401, we will refresh the token and retry the request + BearerTokenHandler.refreshTokenIfUnauthorizedRequestResponse( + data: data, + response: response, + error: error + ) { wasTokenRefreshed in + + if wasTokenRefreshed { + // If the token was refreshed, it's because it was a 401 error, so we refreshed the token, and we are going to retry the request by calling self.execute() + self.execute(apiResponseQueue, completion) + } else { + // If the token was not refreshed, it's because it was not a 401 error, so we send the response to the completion block + completion(result) + } + } + } else { + // If it's an unknown error, we send the response to the completion block + completion(result) + } + + } + } + } + } +} + +class BearerTokenHandler { + private static var bearerToken: String? = nil + + static func refreshTokenIfDoesntExist(completionHandler: @escaping () -> Void) { + if bearerToken != nil { + completionHandler() + } else { + startRefreshingToken { + completionHandler() + } + } + } + + static func refreshTokenIfUnauthorizedRequestResponse(data: Data?, response: URLResponse?, error: Error?, completionHandler: @escaping (Bool) -> Void) { + if let response = response as? HTTPURLResponse, response.statusCode == 401 { + startRefreshingToken { + completionHandler(true) + } + } else { + completionHandler(false) + } + } + + private static func startRefreshingToken(completionHandler: @escaping () -> Void) { + // Get a bearer token + let dummyBearerToken = "..." + + bearerToken = dummyBearerToken + PetstoreClientAPI.customHeaders["Authorization"] = "Bearer \(dummyBearerToken)" + + completionHandler() + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift index 6bc3f45b544..670c5ca54be 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClientTests/FileUtils.swift @@ -18,7 +18,7 @@ class FileUtils { let fileURL = documentsDirectory.appendingPathComponent(fileName) guard let data = image.jpegData(compressionQuality: 1) else { return nil } - //Checks if file exists, removes it if so. + // Checks if file exists, removes it if so. deleteFile(fileURL: fileURL) do { diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/AdditionalPropertiesClass.md index e22d28be1de..1f222244134 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/AdditionalPropertiesClass.md @@ -3,8 +3,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapString** | **[String:String]** | | [optional] -**mapMapString** | [String:[String:String]] | | [optional] +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [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/swift5/urlsessionLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md index d0ab705d4e4..83d9a2873c5 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md @@ -564,7 +564,7 @@ No authorization required # **testInlineAdditionalProperties** ```swift - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` test inline additionalProperties @@ -574,7 +574,7 @@ test inline additionalProperties // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let param = "TODO" // [String:String] | request body +let param = "TODO" // [String: String] | request body // test inline additionalProperties FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in @@ -593,7 +593,7 @@ FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**[String:String]**](String.md) | request body | + **param** | [**[String: String]**](String.md) | request body | ### Return type diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/MapTest.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/MapTest.md index 56213c4113f..73f9e0d50ac 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/MapTest.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/MapTest.md @@ -3,9 +3,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [String:[String:String]] | | [optional] -**mapOfEnumString** | **[String:String]** | | [optional] -**directMap** | **[String:Bool]** | | [optional] +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] **indirectMap** | [**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/swift5/urlsessionLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcffb8ecdbf..3fdfd03f0e3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **UUID** | | [optional] **dateTime** | **Date** | | [optional] -**map** | [String:Animal] | | [optional] +**map** | [String: Animal] | | [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/swift5/urlsessionLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/StoreAPI.md index 36365ca5199..383dda5d3c7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/StoreAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/StoreAPI.md @@ -62,7 +62,7 @@ No authorization required # **getInventory** ```swift - open class func getInventory(completion: @escaping (_ data: [String:Int]?, _ error: Error?) -> Void) + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) ``` Returns pet inventories by status @@ -93,7 +93,7 @@ This endpoint does not need any parameter. ### Return type -**[String:Int]** +**[String: Int]** ### Authorization diff --git a/samples/client/petstore/swift5/urlsessionLibrary/project.yml b/samples/client/petstore/swift5/urlsessionLibrary/project.yml index 892005fdd5a..8e7102001b8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/project.yml +++ b/samples/client/petstore/swift5/urlsessionLibrary/project.yml @@ -3,7 +3,7 @@ targets: PetstoreClient: type: framework platform: iOS - deploymentTarget: "10.0" + deploymentTarget: "9.0" sources: [PetstoreClient] info: path: ./Info.plist diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.gitignore b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.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/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/FILES new file mode 100644 index 00000000000..7f8ebffb302 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION new file mode 100644 index 00000000000..c30f0ec2be7 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/README.md b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/README.md new file mode 100644 index 00000000000..94e4af489d6 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/README.md @@ -0,0 +1,203 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api.module.ts new file mode 100644 index 00000000000..2afb8f64e92 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/api.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/api.ts new file mode 100644 index 00000000000..8e44b64083d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/pet.service.ts new file mode 100644 index 00000000000..b5796e6ddca --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/pet.service.ts @@ -0,0 +1,613 @@ +/** + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +import { ApiResponse } from '../model/models'; +import { Pet } from '../model/models'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'any' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @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, 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.'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @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, 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.'); + } + + let headers = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + headers = headers.set('api_key', String(apiKey)); + } + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @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, 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.'); + } + + let queryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + queryParameters = this.addToHttpParams(queryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + params: queryParameters, + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @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. + * @deprecated + */ + 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.'); + } + + let queryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + queryParameters = this.addToHttpParams(queryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + params: queryParameters, + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @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, 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.'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (api_key) required + credential = this.configuration.lookupCredential('api_key'); + if (credential) { + headers = headers.set('api_key', credential); + } + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * @param body Pet object that needs to be added to the store + * @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, 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.'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param status Updated status of the pet + * @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, 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.'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any; }; + let useForm = false; + let convertFormParamsToString = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + formParams = formParams.append('name', name) as any || formParams; + } + if (status !== undefined) { + formParams = formParams.append('status', status) as any || formParams; + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + convertFormParamsToString ? formParams.toString() : formParams, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @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, 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.'); + } + + let headers = this.defaultHeaders; + + let credential: string | undefined; + // authentication (petstore_auth) required + credential = this.configuration.lookupCredential('petstore_auth'); + if (credential) { + headers = headers.set('Authorization', 'Bearer ' + credential); + } + + 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); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any; }; + let useForm = false; + let convertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + formParams = formParams.append('additionalMetadata', additionalMetadata) as any || formParams; + } + if (file !== undefined) { + formParams = formParams.append('file', file) as any || formParams; + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + convertFormParamsToString ? formParams.toString() : formParams, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/store.service.ts new file mode 100644 index 00000000000..a5f3801ba4b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/store.service.ts @@ -0,0 +1,283 @@ +/** + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +import { Order } from '../model/models'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'any' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * 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 + * @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, 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; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @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, 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; + + let credential: string | undefined; + // authentication (api_key) required + credential = this.configuration.lookupCredential('api_key'); + if (credential) { + headers = headers.set('api_key', credential); + } + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @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, 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; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * @param body order placed for purchasing the pet + * @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, 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; + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/user.service.ts new file mode 100644 index 00000000000..110c576b78a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/api/user.service.ts @@ -0,0 +1,497 @@ +/** + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +import { User } from '../model/models'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'any' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @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, 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; + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @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, 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; + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @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, 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; + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @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, 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; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @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, 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; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @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, 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.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let queryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + queryParameters = this.addToHttpParams(queryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + queryParameters = this.addToHttpParams(queryParameters, + password, 'password'); + } + + let headers = this.defaultHeaders; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + params: queryParameters, + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * @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, 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; + + 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); + } + + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @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, 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.'); + } + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let headers = this.defaultHeaders; + + 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); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + headers = headers.set('Content-Type', httpContentTypeSelected); + } + + let responseType: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + responseType: responseType, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts new file mode 100644 index 00000000000..38126642420 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts @@ -0,0 +1,137 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/encoder.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/git_push.sh b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/index.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/apiResponse.ts new file mode 100644 index 00000000000..682ba478921 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * 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. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/category.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/category.ts new file mode 100644 index 00000000000..b988b6827a0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/category.ts @@ -0,0 +1,21 @@ +/** + * 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. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/models.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/models.ts new file mode 100644 index 00000000000..8607c5dabd0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/order.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/order.ts new file mode 100644 index 00000000000..a29bebe4906 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/order.ts @@ -0,0 +1,37 @@ +/** + * 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. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/pet.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/pet.ts new file mode 100644 index 00000000000..e0404395f91 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/pet.ts @@ -0,0 +1,39 @@ +/** + * 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. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/tag.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/tag.ts new file mode 100644 index 00000000000..b6ff210e8df --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/tag.ts @@ -0,0 +1,21 @@ +/** + * 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. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/user.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/user.ts new file mode 100644 index 00000000000..fce51005300 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/model/user.ts @@ -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. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/variables.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts index 90eb50c42a1..f84920e94e3 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts index 4dfeb54d840..533e9912b14 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts index 8fae3715d1b..3e18bd1692c 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts index 747ca17e206..87070cedb4c 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts @@ -183,7 +183,7 @@ export class Configuration { return undefined; } - get headers(): HTTPHeaders | undefined { + get headers(): HTTPHeaders | undefined { return this.configuration.headers; } diff --git a/samples/meta-codegen/lib/pom.xml b/samples/meta-codegen/lib/pom.xml index 8b0799d9488..6449d694d5d 100644 --- a/samples/meta-codegen/lib/pom.xml +++ b/samples/meta-codegen/lib/pom.xml @@ -121,7 +121,11 @@ UTF-8 +<<<<<<< HEAD 5.1.0-SNAPSHOT +======= + 5.0.1-SNAPSHOT +>>>>>>> origin/master 1.0.0 4.8.1 diff --git a/samples/meta-codegen/usage/.openapi-generator/VERSION b/samples/meta-codegen/usage/.openapi-generator/VERSION index c30f0ec2be7..8dbad87bded 100644 --- a/samples/meta-codegen/usage/.openapi-generator/VERSION +++ b/samples/meta-codegen/usage/.openapi-generator/VERSION @@ -1 +1,5 @@ -5.1.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +5.1.0-SNAPSHOT +======= +5.0.1-SNAPSHOT +>>>>>>> origin/master diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 3c90595a871..86ab78418c2 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -324,7 +324,7 @@ public class ApiClient { * * @param secrets Hash map from authentication name to its secret. */ - public ApiClient configureApiKeys(HashMap secrets) { + public ApiClient configureApiKeys(Map secrets) { for (Map.Entry authEntry : authentications.entrySet()) { Authentication auth = authEntry.getValue(); if (auth instanceof ApiKeyAuth) { diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.gitignore new file mode 100644 index 00000000000..05a17cb8f0a --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.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/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES new file mode 100644 index 00000000000..b6d67848c71 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES @@ -0,0 +1,20 @@ +.gitignore +.rspec +.rubocop.yml +.travis.yml +Gemfile +README.md +Rakefile +docs/UsageApi.md +git_push.sh +lib/x_auth_id_alias.rb +lib/x_auth_id_alias/api/usage_api.rb +lib/x_auth_id_alias/api_client.rb +lib/x_auth_id_alias/api_error.rb +lib/x_auth_id_alias/configuration.rb +lib/x_auth_id_alias/configuration.rb +lib/x_auth_id_alias/version.rb +spec/api_client_spec.rb +spec/configuration_spec.rb +spec/spec_helper.rb +x_auth_id_alias.gemspec diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION new file mode 100644 index 00000000000..c30f0ec2be7 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rspec b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rspec new file mode 100644 index 00000000000..83e16f80447 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rubocop.yml b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rubocop.yml new file mode 100644 index 00000000000..d32b2b1cdab --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.travis.yml new file mode 100644 index 00000000000..3e97f36d171 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.travis.yml @@ -0,0 +1,11 @@ +language: ruby +cache: bundler +rvm: + - 2.3 + - 2.4 + - 2.5 +script: + - bundle install --path vendor/bundle + - bundle exec rspec + - gem build x_auth_id_alias.gemspec + - gem install ./x_auth_id_alias-1.0.0.gem diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Gemfile b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Gemfile new file mode 100644 index 00000000000..c2e3127cdcf --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/README.md new file mode 100644 index 00000000000..18596625507 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/README.md @@ -0,0 +1,116 @@ +# x_auth_id_alias + +XAuthIDAlias - the Ruby gem for the OpenAPI Extension x-auth-id-alias + +This specification shows how to use x-auth-id-alias extension for API keys. + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RubyClientCodegen + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build x_auth_id_alias.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./x_auth_id_alias-1.0.0.gem +``` + +(for development, run `gem install --dev ./x_auth_id_alias-1.0.0.gem` to install the development dependencies) + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem 'x_auth_id_alias', '~> 1.0.0' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/GIT_USER_ID/GIT_REPO_ID, then add the following in the Gemfile: + + gem 'x_auth_id_alias', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: + +```ruby +# Load the gem +require 'x_auth_id_alias' + +# Setup authorization +XAuthIDAlias.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' + + # Configure API key authorization: api_key_query + config.api_key['api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key_query'] = 'Bearer' +end + +api_instance = XAuthIDAlias::UsageApi.new + +begin + #Use any API key + result = api_instance.any_key + p result +rescue XAuthIDAlias::ApiError => e + puts "Exception when calling UsageApi->any_key: #{e}" +end + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*XAuthIDAlias::UsageApi* | [**any_key**](docs/UsageApi.md#any_key) | **GET** /any | Use any API key +*XAuthIDAlias::UsageApi* | [**both_keys**](docs/UsageApi.md#both_keys) | **GET** /both | Use both API keys +*XAuthIDAlias::UsageApi* | [**key_in_header**](docs/UsageApi.md#key_in_header) | **GET** /header | Use API key in header +*XAuthIDAlias::UsageApi* | [**key_in_query**](docs/UsageApi.md#key_in_query) | **GET** /query | Use API key in query + + +## Documentation for Models + + + +## Documentation for Authorization + + +### api_key + + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + +### api_key_query + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Rakefile b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Rakefile new file mode 100644 index 00000000000..c72ca30d454 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/Rakefile @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/docs/UsageApi.md new file mode 100644 index 00000000000..0ec8d9fdfec --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/docs/UsageApi.md @@ -0,0 +1,293 @@ +# XAuthIDAlias::UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**any_key**](UsageApi.md#any_key) | **GET** /any | Use any API key | +| [**both_keys**](UsageApi.md#both_keys) | **GET** /both | Use both API keys | +| [**key_in_header**](UsageApi.md#key_in_header) | **GET** /header | Use API key in header | +| [**key_in_query**](UsageApi.md#key_in_query) | **GET** /query | Use API key in query | + + +## any_key + +> Object any_key + +Use any API key + +Use any API key + +### Examples + +```ruby +require 'time' +require 'x_auth_id_alias' +# setup authorization +XAuthIDAlias.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' + + # Configure API key authorization: api_key_query + config.api_key['api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key_query'] = 'Bearer' +end + +api_instance = XAuthIDAlias::UsageApi.new + +begin + # Use any API key + result = api_instance.any_key + p result +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->any_key: #{e}" +end +``` + +#### Using the any_key_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> any_key_with_http_info + +```ruby +begin + # Use any API key + data, status_code, headers = api_instance.any_key_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => Object +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->any_key_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## both_keys + +> Object both_keys + +Use both API keys + +Use both API keys + +### Examples + +```ruby +require 'time' +require 'x_auth_id_alias' +# setup authorization +XAuthIDAlias.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' + + # Configure API key authorization: api_key_query + config.api_key['api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key_query'] = 'Bearer' +end + +api_instance = XAuthIDAlias::UsageApi.new + +begin + # Use both API keys + result = api_instance.both_keys + p result +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->both_keys: #{e}" +end +``` + +#### Using the both_keys_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> both_keys_with_http_info + +```ruby +begin + # Use both API keys + data, status_code, headers = api_instance.both_keys_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => Object +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->both_keys_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## key_in_header + +> Object key_in_header + +Use API key in header + +Use API key in header + +### Examples + +```ruby +require 'time' +require 'x_auth_id_alias' +# setup authorization +XAuthIDAlias.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' +end + +api_instance = XAuthIDAlias::UsageApi.new + +begin + # Use API key in header + result = api_instance.key_in_header + p result +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->key_in_header: #{e}" +end +``` + +#### Using the key_in_header_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> key_in_header_with_http_info + +```ruby +begin + # Use API key in header + data, status_code, headers = api_instance.key_in_header_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => Object +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->key_in_header_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## key_in_query + +> Object key_in_query + +Use API key in query + +Use API key in query + +### Examples + +```ruby +require 'time' +require 'x_auth_id_alias' +# setup authorization +XAuthIDAlias.configure do |config| + # Configure API key authorization: api_key_query + config.api_key['api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key_query'] = 'Bearer' +end + +api_instance = XAuthIDAlias::UsageApi.new + +begin + # Use API key in query + result = api_instance.key_in_query + p result +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->key_in_query: #{e}" +end +``` + +#### Using the key_in_query_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> key_in_query_with_http_info + +```ruby +begin + # Use API key in query + data, status_code, headers = api_instance.key_in_query_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => Object +rescue XAuthIDAlias::ApiError => e + puts "Error when calling UsageApi->key_in_query_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb new file mode 100644 index 00000000000..2b1ab213ad4 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +# Common files +require 'x_auth_id_alias/api_client' +require 'x_auth_id_alias/api_error' +require 'x_auth_id_alias/version' +require 'x_auth_id_alias/configuration' + +# Models + +# APIs +require 'x_auth_id_alias/api/usage_api' + +module XAuthIDAlias + class << self + # Customize default settings for the SDK using block. + # XAuthIDAlias.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb new file mode 100644 index 00000000000..07aa690e7bd --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb @@ -0,0 +1,250 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +require 'cgi' + +module XAuthIDAlias + class UsageApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Use any API key + # Use any API key + # @param [Hash] opts the optional parameters + # @return [Object] + def any_key(opts = {}) + data, _status_code, _headers = any_key_with_http_info(opts) + data + end + + # Use any API key + # Use any API key + # @param [Hash] opts the optional parameters + # @return [Array<(Object, Integer, Hash)>] Object data, response status code and response headers + def any_key_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UsageApi.any_key ...' + end + # resource path + local_var_path = '/any' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Object' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key', 'api_key_query'] + + new_options = opts.merge( + :operation => :"UsageApi.any_key", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UsageApi#any_key\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Use both API keys + # Use both API keys + # @param [Hash] opts the optional parameters + # @return [Object] + def both_keys(opts = {}) + data, _status_code, _headers = both_keys_with_http_info(opts) + data + end + + # Use both API keys + # Use both API keys + # @param [Hash] opts the optional parameters + # @return [Array<(Object, Integer, Hash)>] Object data, response status code and response headers + def both_keys_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UsageApi.both_keys ...' + end + # resource path + local_var_path = '/both' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Object' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key', 'api_key_query'] + + new_options = opts.merge( + :operation => :"UsageApi.both_keys", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UsageApi#both_keys\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Use API key in header + # Use API key in header + # @param [Hash] opts the optional parameters + # @return [Object] + def key_in_header(opts = {}) + data, _status_code, _headers = key_in_header_with_http_info(opts) + data + end + + # Use API key in header + # Use API key in header + # @param [Hash] opts the optional parameters + # @return [Array<(Object, Integer, Hash)>] Object data, response status code and response headers + def key_in_header_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UsageApi.key_in_header ...' + end + # resource path + local_var_path = '/header' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Object' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key'] + + new_options = opts.merge( + :operation => :"UsageApi.key_in_header", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UsageApi#key_in_header\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Use API key in query + # Use API key in query + # @param [Hash] opts the optional parameters + # @return [Object] + def key_in_query(opts = {}) + data, _status_code, _headers = key_in_query_with_http_info(opts) + data + end + + # Use API key in query + # Use API key in query + # @param [Hash] opts the optional parameters + # @return [Array<(Object, Integer, Hash)>] Object data, response status code and response headers + def key_in_query_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UsageApi.key_in_query ...' + end + # resource path + local_var_path = '/query' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Object' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key_query'] + + new_options = opts.merge( + :operation => :"UsageApi.key_in_query", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UsageApi#key_in_query\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb new file mode 100644 index 00000000000..c369f53d3f8 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb @@ -0,0 +1,390 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +require 'date' +require 'json' +require 'logger' +require 'tempfile' +require 'time' +require 'typhoeus' + +module XAuthIDAlias + class ApiClient + # The Configuration object holding settings to be used in the API client. + attr_accessor :config + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(config = Configuration.default) + @config = config + @user_agent = "OpenAPI-Generator/#{VERSION}/ruby" + @default_headers = { + 'Content-Type' => 'application/json', + 'User-Agent' => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + end + + if opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, opts = {}) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :verbose => @config.debugging + } + + # set custom cert, if provided + req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + request = Typhoeus::Request.new(url, req_opts) + download_file(request) if opts[:return_type] == 'File' + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || + header_params['Content-Type'] == 'multipart/form-data' + data = {} + form_params.each do |key, value| + case value + when ::File, ::Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # The response body is written to the file in chunks in order to handle files which + # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby + # process can use. + # + # @see Configuration#temp_folder_path + def download_file(request) + tempfile = nil + encoding = nil + request.on_headers do |response| + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + @tempfile = tempfile + end + request.on_body do |chunk| + chunk.force_encoding(encoding) + tempfile.write(chunk) + end + request.on_complete do |response| + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + end + end + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + + # handle file downloading - return the File instance processed in request callbacks + # note that response body is empty when the file is written in chunks in request on_body callback + return @tempfile if return_type == 'File' + + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body if return_type == 'String' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date Time).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'Boolean' + data == true + when 'Time' + # parse date time (expecting ISO 8601 format) + Time.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = XAuthIDAlias.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + filename.gsub(/.*[\/\\]/, '') + end + + def build_request_url(path, opts = {}) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + @config.base_url(opts[:operation]) + path + end + + # Update hearder and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array(auth_names).each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] + else fail ArgumentError, 'Authentication token must be in `query` or `header`' + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + json_accept || accepts.join(',') + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # use application/json by default + return 'application/json' if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb new file mode 100644 index 00000000000..1887408c283 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb @@ -0,0 +1,57 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +module XAuthIDAlias + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + + arg.each do |k, v| + instance_variable_set "@#{k}", v + end + else + super arg + end + end + + # Override to_s to display a friendly error message + def to_s + message + end + + def message + if @message.nil? + msg = "Error message: the server returns an error" + else + msg = @message + end + + msg += "\nHTTP status code: #{code}" if code + msg += "\nResponse headers: #{response_headers}" if response_headers + msg += "\nResponse body: #{response_body}" if response_body + + msg + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb new file mode 100644 index 00000000000..2c6a395b390 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb @@ -0,0 +1,317 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +module XAuthIDAlias + class Configuration + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Define server configuration index + attr_accessor :server_index + + # Define server operation configuration index + attr_accessor :server_operation_index + + # Default server variables + attr_accessor :server_variables + + # Default server operation variables + attr_accessor :server_operation_variables + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + attr_accessor :timeout + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + attr_accessor :client_side_validation + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + def initialize + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @server_index = 0 + @server_operation_index = {} + @server_variables = {} + @server_operation_variables = {} + @api_key = {} + @api_key_prefix = {} + @timeout = 0 + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + @params_encoding = nil + @cert_file = nil + @key_file = nil + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = '' if @base_path == '/' + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = nil) + index = server_operation_index.fetch(operation, server_index) + return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if index == nil + + server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{key}" + else + key + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'X-Api-Key', + value: api_key_with_prefix('api_key') + }, + 'api_key_query' => + { + type: 'api_key', + in: 'query', + key: 'api_key', + value: api_key_with_prefix('api_key_query', 'api_key') + }, + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "http://{server}.swagger.io:{port}/v2", + description: "petstore server", + variables: { + server: { + description: "No description provided", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } + }, + { + url: "https://localhost:8080/{version}", + description: "The local server", + variables: { + version: { + description: "No description provided", + default_value: "v2", + enum_values: [ + "v1", + "v2" + ] + } + } + } + ] + end + + def operation_server_settings + { + } + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {}, servers = nil) + servers = server_settings if servers == nil + + # check array index out of bound + if (index < 0 || index >= servers.size) + fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}" + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}." + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb new file mode 100644 index 00000000000..07aeba8c8f0 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb @@ -0,0 +1,15 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +module XAuthIDAlias + VERSION = '1.0.0' +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api/usage_api_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api/usage_api_spec.rb new file mode 100644 index 00000000000..03e3ed32596 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api/usage_api_spec.rb @@ -0,0 +1,79 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.0.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for XAuthIDAlias::UsageApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'UsageApi' do + before do + # run before each test + @api_instance = XAuthIDAlias::UsageApi.new + end + + after do + # run after each test + end + + describe 'test an instance of UsageApi' do + it 'should create an instance of UsageApi' do + expect(@api_instance).to be_instance_of(XAuthIDAlias::UsageApi) + end + end + + # unit tests for any_key + # Use any API key + # Use any API key + # @param [Hash] opts the optional parameters + # @return [Object] + describe 'any_key test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for both_keys + # Use both API keys + # Use both API keys + # @param [Hash] opts the optional parameters + # @return [Object] + describe 'both_keys test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for key_in_header + # Use API key in header + # Use API key in header + # @param [Hash] opts the optional parameters + # @return [Object] + describe 'key_in_header test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for key_in_query + # Use API key in query + # Use API key in query + # @param [Hash] opts the optional parameters + # @return [Object] + describe 'key_in_query test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb new file mode 100644 index 00000000000..1e0b72d48a7 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb @@ -0,0 +1,226 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +require 'spec_helper' + +describe XAuthIDAlias::ApiClient do + context 'initialization' do + context 'URL stuff' do + context 'host' do + it 'removes http from host' do + XAuthIDAlias.configure { |c| c.host = 'http://example.com' } + expect(XAuthIDAlias::Configuration.default.host).to eq('example.com') + end + + it 'removes https from host' do + XAuthIDAlias.configure { |c| c.host = 'https://wookiee.com' } + expect(XAuthIDAlias::ApiClient.default.config.host).to eq('wookiee.com') + end + + it 'removes trailing path from host' do + XAuthIDAlias.configure { |c| c.host = 'hobo.com/v4' } + expect(XAuthIDAlias::Configuration.default.host).to eq('hobo.com') + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + XAuthIDAlias.configure { |c| c.base_path = 'v4/dog' } + expect(XAuthIDAlias::Configuration.default.base_path).to eq('/v4/dog') + end + + it "doesn't prepend a slash if one is already there" do + XAuthIDAlias.configure { |c| c.base_path = '/v4/dog' } + expect(XAuthIDAlias::Configuration.default.base_path).to eq('/v4/dog') + end + + it "ends up as a blank string if nil" do + XAuthIDAlias.configure { |c| c.base_path = nil } + expect(XAuthIDAlias::Configuration.default.base_path).to eq('') + end + end + end + end + + describe 'params_encoding in #build_request' do + let(:config) { XAuthIDAlias::Configuration.new } + let(:api_client) { XAuthIDAlias::ApiClient.new(config) } + + it 'defaults to nil' do + expect(XAuthIDAlias::Configuration.default.params_encoding).to eq(nil) + expect(config.params_encoding).to eq(nil) + + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(nil) + end + + it 'can be customized' do + config.params_encoding = :multi + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(:multi) + end + end + + describe 'timeout in #build_request' do + let(:config) { XAuthIDAlias::Configuration.new } + let(:api_client) { XAuthIDAlias::ApiClient.new(config) } + + it 'defaults to 0' do + expect(XAuthIDAlias::Configuration.default.timeout).to eq(0) + expect(config.timeout).to eq(0) + + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(0) + end + + it 'can be customized' do + config.timeout = 100 + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(100) + end + end + + describe '#deserialize' do + it "handles Array" do + api_client = XAuthIDAlias::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + expect(data).to be_instance_of(Array) + expect(data).to eq([12, 34]) + end + + it 'handles Array>' do + api_client = XAuthIDAlias::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + expect(data).to be_instance_of(Array) + expect(data).to eq([[12, 34], [56]]) + end + + it 'handles Hash' do + api_client = XAuthIDAlias::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + expect(data).to be_instance_of(Hash) + expect(data).to eq(:message => 'Hello') + end + end + + describe "#object_to_hash" do + it 'ignores nils and includes empty arrays' do + # uncomment below to test object_to_hash for model + # api_client = XAuthIDAlias::ApiClient.new + # _model = XAuthIDAlias::ModelName.new + # update the model attribute below + # _model.id = 1 + # update the expected value (hash) below + # expected = {id: 1, name: '', tags: []} + # expect(api_client.object_to_hash(_model)).to eq(expected) + end + end + + describe '#build_collection_param' do + let(:param) { ['aa', 'bb', 'cc'] } + let(:api_client) { XAuthIDAlias::ApiClient.new } + + it 'works for csv' do + expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') + end + + it 'works for ssv' do + expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') + end + + it 'works for tsv' do + expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") + end + + it 'works for pipes' do + expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') + end + + it 'works for multi' do + expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) + end + + it 'fails for invalid collection format' do + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + end + end + + describe '#json_mime?' do + let(:api_client) { XAuthIDAlias::ApiClient.new } + + it 'works' do + expect(api_client.json_mime?(nil)).to eq false + expect(api_client.json_mime?('')).to eq false + + expect(api_client.json_mime?('application/json')).to eq true + expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true + expect(api_client.json_mime?('APPLICATION/JSON')).to eq true + + expect(api_client.json_mime?('application/xml')).to eq false + expect(api_client.json_mime?('text/plain')).to eq false + expect(api_client.json_mime?('application/jsonp')).to eq false + end + end + + describe '#select_header_accept' do + let(:api_client) { XAuthIDAlias::ApiClient.new } + + it 'works' do + expect(api_client.select_header_accept(nil)).to be_nil + expect(api_client.select_header_accept([])).to be_nil + + expect(api_client.select_header_accept(['application/json'])).to eq('application/json') + expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + + expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') + end + end + + describe '#select_header_content_type' do + let(:api_client) { XAuthIDAlias::ApiClient.new } + + it 'works' do + expect(api_client.select_header_content_type(nil)).to eq('application/json') + expect(api_client.select_header_content_type([])).to eq('application/json') + + expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') + expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') + end + end + + describe '#sanitize_filename' do + let(:api_client) { XAuthIDAlias::ApiClient.new } + + it 'works' do + expect(api_client.sanitize_filename('sun')).to eq('sun') + expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb new file mode 100644 index 00000000000..daf94393572 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb @@ -0,0 +1,42 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +require 'spec_helper' + +describe XAuthIDAlias::Configuration do + let(:config) { XAuthIDAlias::Configuration.default } + + before(:each) do + # uncomment below to setup host and base_path + # require 'URI' + # uri = URI.parse("http://petstore.swagger.io:80/v2") + # XAuthIDAlias.configure do |c| + # c.host = uri.host + # c.base_path = uri.path + # end + end + + describe '#base_url' do + it 'should have the default value' do + # uncomment below to test default value of the base path + # expect(config.base_url).to eq("http://petstore.swagger.io:80/v2") + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + # uncomment below to test trailing slashes + # expect(config.base_url).to eq("http://petstore.swagger.io:80/v2") + end + end + end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb new file mode 100644 index 00000000000..6dda2b19c46 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb @@ -0,0 +1,111 @@ +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +# load the gem +require 'x_auth_id_alias' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec new file mode 100644 index 00000000000..e3a6e8d9723 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec @@ -0,0 +1,38 @@ +# -*- encoding: utf-8 -*- + +=begin +#OpenAPI Extension x-auth-id-alias + +#This specification shows how to use x-auth-id-alias extension for API keys. + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 5.1.0-SNAPSHOT + +=end + +$:.push File.expand_path("../lib", __FILE__) +require "x_auth_id_alias/version" + +Gem::Specification.new do |s| + s.name = "x_auth_id_alias" + s.version = XAuthIDAlias::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["OpenAPI-Generator"] + s.email = [""] + s.homepage = "https://openapi-generator.tech" + s.summary = "OpenAPI Extension x-auth-id-alias Ruby Gem" + s.description = "This specification shows how to use x-auth-id-alias extension for API keys." + s.license = "Unlicense" + s.required_ruby_version = ">= 2.4" + + s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' + + s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0' + + s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb index 1b52629eda4..8ae4ab399d1 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb @@ -307,7 +307,7 @@ module DynamicServers case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] - else fail ArgumentError, 'Authentication token must be in `query` of `header`' + else fail ArgumentError, 'Authentication token must be in `query` or `header`' end end end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb index 875eef66683..5fa24c5eee9 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb @@ -197,11 +197,13 @@ module DynamicServers # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth - def api_key_with_prefix(param_name) + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + "#{@api_key_prefix[param_name]} #{key}" else - @api_key[param_name] + key end end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb index dbf16eeecd7..5fc4263b17a 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb @@ -307,7 +307,7 @@ module Petstore case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] - else fail ArgumentError, 'Authentication token must be in `query` of `header`' + else fail ArgumentError, 'Authentication token must be in `query` or `header`' end end end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb index 3ed00b33bb7..226fdcab1d2 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb @@ -197,11 +197,13 @@ module Petstore # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth - def api_key_with_prefix(param_name) + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + "#{@api_key_prefix[param_name]} #{key}" else - @api_key[param_name] + key end end diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml index 655cb67bd88..a611887d3ac 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/analysis_options.yaml @@ -1 +1,9 @@ -analyzer: \ No newline at end of file +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject.md deleted file mode 100644 index 9aa480dee58..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [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/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject1.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject1.md deleted file mode 100644 index 89db64f1214..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/InlineObject1.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject1 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | [**Uint8List**](Uint8List.md) | file to upload | [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/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api.dart index fb9635ab642..2422d33a0f3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library openapi.api; import 'package:dio/dio.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart index 29837e6354b..65752e18bae 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -29,33 +36,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(pet); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, pet); final jsonpet = json.encode(serializedBody); bodyData = jsonpet; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -70,8 +78,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Pet); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Pet) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -100,27 +111,27 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; headerParams[r'api_key'] = apiKey; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -151,27 +162,27 @@ class PetApi { }) async { final String _path = '/pet/findByStatus'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'status'] = status; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -188,7 +199,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -216,27 +232,27 @@ class PetApi { }) async { final String _path = '/pet/findByTags'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'tags'] = tags; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -253,7 +269,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -281,26 +302,26 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -317,8 +338,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Pet); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Pet) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -346,33 +370,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(pet); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, pet); final jsonpet = json.encode(serializedBody); bodyData = jsonpet; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -387,8 +412,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Pet); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Pet) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -418,33 +446,33 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['name'] = parameterToString(_serializers, name); formData['status'] = parameterToString(_serializers, status); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -477,20 +505,20 @@ class PetApi { }) async { final String _path = '/pet/{petId}/uploadImage'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'multipart/form-data', ]; - final Map formData = {}; + final formData = {}; if (additionalMetadata != null) { formData[r'additionalMetadata'] = parameterToString(_serializers, additionalMetadata); } @@ -499,15 +527,15 @@ class PetApi { } bodyData = FormData.fromMap(formData); - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -522,8 +550,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ApiResponse); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ApiResponse) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart index cc30e5b5597..ba3f241333e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,26 +33,26 @@ class StoreApi { }) async { final String _path = '/store/order/{orderId}'.replaceAll('{' r'orderId' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -70,26 +77,26 @@ class StoreApi { }) async { final String _path = '/store/inventory'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -108,7 +115,12 @@ class StoreApi { ).then((response) { const collectionType = BuiltMap; const type = FullType(collectionType, [FullType(String), FullType(int)]); - final BuiltMap data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltMap; return Response>( data: data, @@ -136,26 +148,26 @@ class StoreApi { }) async { final String _path = '/store/order/{orderId}'.replaceAll('{' r'orderId' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -165,8 +177,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -194,32 +209,33 @@ class StoreApi { }) async { final String _path = '/store/order'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(order); + final bodySerializer = _serializers.serializerForType(Order) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, order); final jsonorder = json.encode(serializedBody); bodyData = jsonorder; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -229,8 +245,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart index c7ba72a9a88..cb890e1846c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,32 +33,33 @@ class UserApi { }) async { final String _path = '/user'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(user); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, user); final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -84,16 +92,16 @@ class UserApi { }) async { final String _path = '/user/createWithArray'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; @@ -102,15 +110,15 @@ class UserApi { final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -143,16 +151,16 @@ class UserApi { }) async { final String _path = '/user/createWithList'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; @@ -161,15 +169,15 @@ class UserApi { final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -202,26 +210,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -254,26 +262,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -283,8 +291,11 @@ class UserApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(User); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(User) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -313,28 +324,28 @@ class UserApi { }) async { final String _path = '/user/login'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'username'] = username; queryParams[r'password'] = password; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -371,26 +382,26 @@ class UserApi { }) async { final String _path = '/user/logout'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -424,32 +435,33 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(user); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, user); final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart index e99530f6c39..361fab65af5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api_util.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:convert'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart index 6cde089a9a1..76c1fc890c8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/api_key_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class ApiKeyAuthInterceptor extends AuthInterceptor { Map apiKeys = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "apiKey"); - for (var info in authInfo) { - final authName = info["name"]; - final authKeyName = info["keyName"]; - final authWhere = info["where"]; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; final apiKey = apiKeys[authName]; if (apiKey != null) { if (authWhere == 'query') { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart index 703127c762b..1cca446ee78 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/auth.dart @@ -1,4 +1,9 @@ -import 'dart:async'; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import import 'package:dio/dio.dart'; @@ -8,11 +13,11 @@ abstract class AuthInterceptor extends Interceptor { * Can return null if type is not present on auth data or if route doesn't need authentication */ List> getAuthInfo(RequestOptions route, String type) { - if (route.extra.containsKey("secure")) { - final auth = route.extra["secure"]; - List> results = []; - for (var info in auth) { - if(info["type"] == type) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + final results = >[]; + for (final info in auth) { + if (info['type'] == type) { results.add(info); } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart index 14334a2d288..1f9a2e281f5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/basic_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:openapi/auth/auth.dart'; @@ -14,13 +21,13 @@ class BasicAuthInterceptor extends AuthInterceptor { Map authInfo = {}; @override - Future onRequest(RequestOptions options) { + Future onRequest(RequestOptions options) { final metadataAuthInfo = getAuthInfo(options, 'basic'); - for (var info in metadataAuthInfo) { - final authName = info['name']; + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; final basicAuthInfo = authInfo[authName]; - if(basicAuthInfo != null) { - String basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); + if (basicAuthInfo != null) { + final basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); options.headers['Authorization'] = basicAuth; break; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart index 3fb06b580b9..481447bffdf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/auth/oauth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class OAuthInterceptor extends AuthInterceptor { Map tokens = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "oauth"); - for (var info in authInfo) { - final token = tokens[info["name"]]; - if(token != null) { - options.headers["Authorization"] = "Bearer ${token}"; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'oauth'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; break; } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart index 137b6de21ab..c5bc1e59646 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/api_response.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -22,7 +29,7 @@ abstract class ApiResponse implements Built { static void _initializeBuilder(ApiResponseBuilder b) => b; - factory ApiResponse([updates(ApiResponseBuilder b)]) = _$ApiResponse; + factory ApiResponse([void updates(ApiResponseBuilder b)]) = _$ApiResponse; static Serializer get serializer => _$apiResponseSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart index c716072d768..ddd15d54a53 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/category.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Category implements Built { static void _initializeBuilder(CategoryBuilder b) => b; - factory Category([updates(CategoryBuilder b)]) = _$Category; + factory Category([void updates(CategoryBuilder b)]) = _$Category; static Serializer get serializer => _$categorySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object.dart deleted file mode 100644 index b1477f60e8c..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object.g.dart'; - -abstract class InlineObject implements Built { - - /// Updated name of the pet - @nullable - @BuiltValueField(wireName: r'name') - String get name; - - /// Updated status of the pet - @nullable - @BuiltValueField(wireName: r'status') - String get status; - - // Boilerplate code needed to wire-up generated code - InlineObject._(); - - static void _initializeBuilder(InlineObjectBuilder b) => b; - - factory InlineObject([updates(InlineObjectBuilder b)]) = _$InlineObject; - static Serializer get serializer => _$inlineObjectSerializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object1.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object1.dart deleted file mode 100644 index 2eadc367d2d..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/inline_object1.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:typed_data'; -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object1.g.dart'; - -abstract class InlineObject1 implements Built { - - /// Additional data to pass to server - @nullable - @BuiltValueField(wireName: r'additionalMetadata') - String get additionalMetadata; - - /// file to upload - @nullable - @BuiltValueField(wireName: r'file') - Uint8List get file; - - // Boilerplate code needed to wire-up generated code - InlineObject1._(); - - static void _initializeBuilder(InlineObject1Builder b) => b; - - factory InlineObject1([updates(InlineObject1Builder b)]) = _$InlineObject1; - static Serializer get serializer => _$inlineObject1Serializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart index 517fba8eb73..f26c6213820 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/order.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -38,7 +45,7 @@ abstract class Order implements Built { static void _initializeBuilder(OrderBuilder b) => b ..complete = false; - factory Order([updates(OrderBuilder b)]) = _$Order; + factory Order([void updates(OrderBuilder b)]) = _$Order; static Serializer get serializer => _$orderSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart index 1fb992db794..98757f5e7ce 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/pet.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/tag.dart'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/model/category.dart'; @@ -39,7 +46,7 @@ abstract class Pet implements Built { static void _initializeBuilder(PetBuilder b) => b; - factory Pet([updates(PetBuilder b)]) = _$Pet; + factory Pet([void updates(PetBuilder b)]) = _$Pet; static Serializer get serializer => _$petSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart index 8149a7d3498..528acd843e7 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/tag.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Tag implements Built { static void _initializeBuilder(TagBuilder b) => b; - factory Tag([updates(TagBuilder b)]) = _$Tag; + factory Tag([void updates(TagBuilder b)]) = _$Tag; static Serializer get serializer => _$tagSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart index 3fd4092d546..93259a43019 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/model/user.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -43,7 +50,7 @@ abstract class User implements Built { static void _initializeBuilder(UserBuilder b) => b; - factory User([updates(UserBuilder b)]) = _$User; + factory User([void updates(UserBuilder b)]) = _$User; static Serializer get serializer => _$userSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart index 5db183b7438..b3c6cf6e1f1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/serializers.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library serializers; import 'package:built_value/iso_8601_date_time_serializer.dart'; @@ -13,43 +20,31 @@ import 'package:openapi/model/pet.dart'; import 'package:openapi/model/tag.dart'; import 'package:openapi/model/user.dart'; - part 'serializers.g.dart'; @SerializersFor(const [ -ApiResponse, -Category, -Order, -Pet, -Tag, -User, - + ApiResponse, + Category, + Order, + Pet, + Tag, + User, ]) - -//allow all models to be serialized within a list Serializers serializers = (_$serializers.toBuilder() -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ApiResponse)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Category)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Order)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Pet)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Tag)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(User)]), -() => new ListBuilder()) - -..add(Iso8601DateTimeSerializer()) -).build(); + ..addBuilderFactory( + const FullType(BuiltList, [FullType(Pet)]), + () => ListBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltMap, [FullType(String), FullType(int)]), + () => MapBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), + ) + ..add(Iso8601DateTimeSerializer())) + .build(); Serializers standardSerializers = -(serializers.toBuilder() -..addPlugin(StandardJsonPlugin())).build(); + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pom.xml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pom.xml index 83864912ce7..190da84cc44 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pom.xml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pom.xml @@ -67,6 +67,22 @@ + + dartanalyzer + integration-test + + exec + + + dartanalyzer + + --fatal-infos + --options + analysis_options.yaml + . + + + pub-test integration-test diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml index 20b190aa1d3..c7c5c5aec83 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml @@ -2,7 +2,7 @@ name: openapi version: 1.0.0 description: OpenAPI API client environment: - sdk: ">=2.3.0 <3.0.0" + sdk: ">=2.6.0 <3.0.0" dependencies: dio: ^3.0.9 built_value: ^7.1.0 diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/api_response_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/api_response_test.dart index d80b2976160..39d3ffc2941 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/api_response_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/api_response_test.dart @@ -6,17 +6,17 @@ void main() { final instance = ApiResponse(); group(ApiResponse, () { - // int code (default value: null) + // int code test('to test the property `code`', () async { // TODO }); - // String type (default value: null) + // String type test('to test the property `type`', () async { // TODO }); - // String message (default value: null) + // String message test('to test the property `message`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/category_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/category_test.dart index 571e020bf63..cf8f893d513 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/category_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/category_test.dart @@ -6,12 +6,12 @@ void main() { final instance = Category(); group(Category, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // String name (default value: null) + // String name test('to test the property `name`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/order_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/order_test.dart index ea9ac6e14eb..25b2cc396f3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/order_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/order_test.dart @@ -6,28 +6,28 @@ void main() { final instance = Order(); group(Order, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // int petId (default value: null) + // int petId test('to test the property `petId`', () async { // TODO }); - // int quantity (default value: null) + // int quantity test('to test the property `quantity`', () async { // TODO }); - // DateTime shipDate (default value: null) + // DateTime shipDate test('to test the property `shipDate`', () async { // TODO }); // Order Status - // String status (default value: null) + // String status test('to test the property `status`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/pet_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/pet_test.dart index 63cfc070e93..9d5b6e4dd4a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/pet_test.dart @@ -6,33 +6,33 @@ void main() { final instance = Pet(); group(Pet, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // Category category (default value: null) + // Category category test('to test the property `category`', () async { // TODO }); - // String name (default value: null) + // String name test('to test the property `name`', () async { // TODO }); - // BuiltList photoUrls (default value: const []) + // BuiltList photoUrls test('to test the property `photoUrls`', () async { // TODO }); - // BuiltList tags (default value: const []) + // BuiltList tags test('to test the property `tags`', () async { // TODO }); // pet status in the store - // String status (default value: null) + // String status test('to test the property `status`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/tag_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/tag_test.dart index c2757a71863..0dbda6e4986 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/tag_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/tag_test.dart @@ -6,12 +6,12 @@ void main() { final instance = Tag(); group(Tag, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // String name (default value: null) + // String name test('to test the property `name`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/user_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/user_test.dart index b598e7f7fef..09e720b625c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/test/user_test.dart @@ -6,43 +6,43 @@ void main() { final instance = User(); group(User, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // String username (default value: null) + // String username test('to test the property `username`', () async { // TODO }); - // String firstName (default value: null) + // String firstName test('to test the property `firstName`', () async { // TODO }); - // String lastName (default value: null) + // String lastName test('to test the property `lastName`', () async { // TODO }); - // String email (default value: null) + // String email test('to test the property `email`', () async { // TODO }); - // String password (default value: null) + // String password test('to test the property `password`', () async { // TODO }); - // String phone (default value: null) + // String phone test('to test the property `phone`', () async { // TODO }); // User Status - // int userStatus (default value: null) + // int userStatus test('to test the property `userStatus`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml index 655cb67bd88..a611887d3ac 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml @@ -1 +1,9 @@ -analyzer: \ No newline at end of file +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject.md deleted file mode 100644 index 9aa480dee58..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject1.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject1.md deleted file mode 100644 index 89db64f1214..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject1.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject1 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | [**Uint8List**](Uint8List.md) | file to upload | [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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject2.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject2.md deleted file mode 100644 index 7bea7e9566e..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject2.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject2 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumFormStringArray** | **BuiltList** | Form parameter enum test (string array) | [optional] -**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to '-efg'] - -[[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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject3.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject3.md deleted file mode 100644 index a8915eb5d38..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject3.md +++ /dev/null @@ -1,28 +0,0 @@ -# openapi.model.InlineObject3 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **int** | None | [optional] -**int32** | **int** | None | [optional] -**int64** | **int** | None | [optional] -**number** | **num** | None | -**float** | **double** | None | [optional] -**double_** | **double** | None | -**string** | **String** | None | [optional] -**patternWithoutDelimiter** | **String** | None | -**byte** | **String** | None | -**binary** | [**Uint8List**](Uint8List.md) | None | [optional] -**date** | [**DateTime**](DateTime.md) | None | [optional] -**dateTime** | [**DateTime**](DateTime.md) | None | [optional] -**password** | **String** | None | [optional] -**callback** | **String** | None | [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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject4.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject4.md deleted file mode 100644 index 3823ffff979..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject4.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject4 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **String** | field1 | -**param2** | **String** | field2 | - -[[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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject5.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject5.md deleted file mode 100644 index e5daf8da8a1..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/InlineObject5.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject5 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**requiredFile** | [**Uint8List**](Uint8List.md) | file to upload | - -[[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/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api.dart index b614ff61186..3e1dec02f81 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library openapi.api; import 'package:dio/dio.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart index bb7458c32f1..16e34300387 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -25,32 +32,33 @@ class AnotherFakeApi { }) async { final String _path = '/another-fake/dummy'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(modelClient); + final bodySerializer = _serializers.serializerForType(ModelClient) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, modelClient); final jsonmodelClient = json.encode(serializedBody); bodyData = jsonmodelClient; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'patch'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -60,8 +68,11 @@ class AnotherFakeApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ModelClient); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ModelClient) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart index 4ddaced7faf..1e93ce8718a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -24,26 +31,26 @@ class DefaultApi { }) async { final String _path = '/foo'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -53,8 +60,11 @@ class DefaultApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(InlineResponseDefault); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(InlineResponseDefault) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart index 4347da0f254..ade787a58a4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -32,26 +39,26 @@ class FakeApi { }) async { final String _path = '/fake/health'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -61,8 +68,11 @@ class FakeApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(HealthCheckResult); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(HealthCheckResult) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -92,35 +102,36 @@ class FakeApi { }) async { final String _path = '/fake/http-signature-test'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; headerParams[r'header_1'] = header1; queryParams[r'query_1'] = query1; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(pet); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, pet); final jsonpet = json.encode(serializedBody); bodyData = jsonpet; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'http', 'name': 'http_signature_test', @@ -151,32 +162,32 @@ class FakeApi { }) async { final String _path = '/fake/outer/boolean'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(body); + var serializedBody = body; final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -214,32 +225,33 @@ class FakeApi { }) async { final String _path = '/fake/outer/composite'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(outerComposite); + final bodySerializer = _serializers.serializerForType(OuterComposite) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, outerComposite); final jsonouterComposite = json.encode(serializedBody); bodyData = jsonouterComposite; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -249,8 +261,11 @@ class FakeApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(OuterComposite); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(OuterComposite) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -278,32 +293,32 @@ class FakeApi { }) async { final String _path = '/fake/outer/number'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(body); + var serializedBody = body; final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -341,32 +356,32 @@ class FakeApi { }) async { final String _path = '/fake/outer/string'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(body); + var serializedBody = body; final jsonbody = json.encode(serializedBody); bodyData = jsonbody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -404,32 +419,33 @@ class FakeApi { }) async { final String _path = '/fake/body-with-file-schema'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(fileSchemaTestClass); + final bodySerializer = _serializers.serializerForType(FileSchemaTestClass) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, fileSchemaTestClass); final jsonfileSchemaTestClass = json.encode(serializedBody); bodyData = jsonfileSchemaTestClass; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -456,33 +472,34 @@ class FakeApi { }) async { final String _path = '/fake/body-with-query-params'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'query'] = query; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(user); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, user); final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -508,32 +525,33 @@ class FakeApi { }) async { final String _path = '/fake'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(modelClient); + final bodySerializer = _serializers.serializerForType(ModelClient) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, modelClient); final jsonmodelClient = json.encode(serializedBody); bodyData = jsonmodelClient; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'patch'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -543,8 +561,11 @@ class FakeApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ModelClient); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ModelClient) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -585,20 +606,20 @@ class FakeApi { }) async { final String _path = '/fake'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['integer'] = parameterToString(_serializers, integer); formData['int32'] = parameterToString(_serializers, int32); formData['int64'] = parameterToString(_serializers, int64); @@ -615,15 +636,15 @@ class FakeApi { formData['callback'] = parameterToString(_serializers, callback); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'http', 'name': 'http_basic_test', @@ -661,8 +682,8 @@ class FakeApi { }) async { final String _path = '/fake'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; @@ -673,27 +694,27 @@ class FakeApi { queryParams[r'enum_query_string'] = enumQueryString; queryParams[r'enum_query_integer'] = enumQueryInteger; queryParams[r'enum_query_double'] = enumQueryDouble; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['enum_form_string_array'] = parameterToString(_serializers, enumFormStringArray); formData['enum_form_string'] = parameterToString(_serializers, enumFormString); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -724,8 +745,8 @@ class FakeApi { }) async { final String _path = '/fake'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; @@ -736,20 +757,20 @@ class FakeApi { queryParams[r'required_int64_group'] = requiredInt64Group; queryParams[r'string_group'] = stringGroup; queryParams[r'int64_group'] = int64Group; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'http', 'name': 'bearer_test', @@ -780,32 +801,33 @@ class FakeApi { }) async { final String _path = '/fake/inline-additionalProperties'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(requestBody); + const type = FullType(BuiltMap, [FullType(String), FullType(String)]); + final serializedBody = _serializers.serialize(requestBody, specifiedType: type); final jsonrequestBody = json.encode(serializedBody); bodyData = jsonrequestBody; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -832,33 +854,33 @@ class FakeApi { }) async { final String _path = '/fake/jsonFormData'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['param'] = parameterToString(_serializers, param); formData['param2'] = parameterToString(_serializers, param2); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -888,8 +910,8 @@ class FakeApi { }) async { final String _path = '/fake/test-query-paramters'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; @@ -899,20 +921,20 @@ class FakeApi { queryParams[r'http'] = http; queryParams[r'url'] = url; queryParams[r'context'] = context; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index 568b5043f6d..222097970a1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -25,32 +32,33 @@ class FakeClassnameTags123Api { }) async { final String _path = '/fake_classname_test'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(modelClient); + final bodySerializer = _serializers.serializerForType(ModelClient) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, modelClient); final jsonmodelClient = json.encode(serializedBody); bodyData = jsonmodelClient; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'patch'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key_query', @@ -67,8 +75,11 @@ class FakeClassnameTags123Api { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ModelClient); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ModelClient) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart index 7f79f93ca0a..b5536c892ec 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -29,33 +36,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(pet); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, pet); final jsonpet = json.encode(serializedBody); bodyData = jsonpet; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -87,27 +95,27 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; headerParams[r'api_key'] = apiKey; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -138,27 +146,27 @@ class PetApi { }) async { final String _path = '/pet/findByStatus'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'status'] = status; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -175,7 +183,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -203,27 +216,27 @@ class PetApi { }) async { final String _path = '/pet/findByTags'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'tags'] = tags; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -240,7 +253,12 @@ class PetApi { ).then((response) { const collectionType = BuiltList; const type = FullType(collectionType, [FullType(Pet)]); - final BuiltList data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltList; return Response>( data: data, @@ -268,26 +286,26 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -304,8 +322,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Pet); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Pet) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -333,33 +354,34 @@ class PetApi { }) async { final String _path = '/pet'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', 'application/xml', ]; - final serializedBody = _serializers.serialize(pet); + final bodySerializer = _serializers.serializerForType(Pet) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, pet); final jsonpet = json.encode(serializedBody); bodyData = jsonpet; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -392,33 +414,33 @@ class PetApi { }) async { final String _path = '/pet/{petId}'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/x-www-form-urlencoded', ]; - final Map formData = {}; + final formData = {}; formData['name'] = parameterToString(_serializers, name); formData['status'] = parameterToString(_serializers, status); bodyData = formData; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -451,20 +473,20 @@ class PetApi { }) async { final String _path = '/pet/{petId}/uploadImage'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'multipart/form-data', ]; - final Map formData = {}; + final formData = {}; if (additionalMetadata != null) { formData[r'additionalMetadata'] = parameterToString(_serializers, additionalMetadata); } @@ -473,15 +495,15 @@ class PetApi { } bodyData = FormData.fromMap(formData); - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -496,8 +518,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ApiResponse); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ApiResponse) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -527,20 +552,20 @@ class PetApi { }) async { final String _path = '/fake/{petId}/uploadImageWithRequiredFile'.replaceAll('{' r'petId' '}', petId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'multipart/form-data', ]; - final Map formData = {}; + final formData = {}; if (additionalMetadata != null) { formData[r'additionalMetadata'] = parameterToString(_serializers, additionalMetadata); } @@ -549,15 +574,15 @@ class PetApi { } bodyData = FormData.fromMap(formData); - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'oauth2', 'name': 'petstore_auth', @@ -572,8 +597,11 @@ class PetApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(ApiResponse); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(ApiResponse) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart index 98f0a4f507b..a1bea34d14f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,26 +33,26 @@ class StoreApi { }) async { final String _path = '/store/order/{order_id}'.replaceAll('{' r'order_id' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -70,26 +77,26 @@ class StoreApi { }) async { final String _path = '/store/inventory'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [ + extra: { + 'secure': >[ { 'type': 'apiKey', 'name': 'api_key', @@ -108,7 +115,12 @@ class StoreApi { ).then((response) { const collectionType = BuiltMap; const type = FullType(collectionType, [FullType(String), FullType(int)]); - final BuiltMap data = _serializers.deserialize(response.data is String ? jsonDecode(response.data) : response.data, specifiedType: type); + final data = _serializers.deserialize( + response.data is String + ? jsonDecode(response.data as String) + : response.data, + specifiedType: type, + ) as BuiltMap; return Response>( data: data, @@ -136,26 +148,26 @@ class StoreApi { }) async { final String _path = '/store/order/{order_id}'.replaceAll('{' r'order_id' '}', orderId.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -165,8 +177,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -194,32 +209,33 @@ class StoreApi { }) async { final String _path = '/store/order'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(order); + final bodySerializer = _serializers.serializerForType(Order) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, order); final jsonorder = json.encode(serializedBody); bodyData = jsonorder; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -229,8 +245,11 @@ class StoreApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(Order); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(Order) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart index 52a48e251df..87dbb0b8d14 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -26,32 +33,33 @@ class UserApi { }) async { final String _path = '/user'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(user); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, user); final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -77,16 +85,16 @@ class UserApi { }) async { final String _path = '/user/createWithArray'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; @@ -95,15 +103,15 @@ class UserApi { final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -129,16 +137,16 @@ class UserApi { }) async { final String _path = '/user/createWithList'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; @@ -147,15 +155,15 @@ class UserApi { final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'post'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -181,26 +189,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'delete'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -226,26 +234,26 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -255,8 +263,11 @@ class UserApi { onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, ).then((response) { - final serializer = _serializers.serializerForType(User); - final data = _serializers.deserializeWith(serializer, response.data is String ? jsonDecode(response.data) : response.data); + final serializer = _serializers.serializerForType(User) as Serializer; + final data = _serializers.deserializeWith( + serializer, + response.data is String ? jsonDecode(response.data as String) : response.data, + ); return Response( data: data, @@ -285,28 +296,28 @@ class UserApi { }) async { final String _path = '/user/login'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; queryParams[r'username'] = username; queryParams[r'password'] = password; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -343,26 +354,26 @@ class UserApi { }) async { final String _path = '/user/logout'; - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = []; + final contentTypes = []; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'get'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, @@ -389,32 +400,33 @@ class UserApi { }) async { final String _path = '/user/{username}'.replaceAll('{' r'username' '}', username.toString()); - final Map queryParams = {}; - final Map headerParams = { + final queryParams = {}; + final headerParams = { if (headers != null) ...headers, }; dynamic bodyData; - queryParams.removeWhere((key, value) => value == null); - headerParams.removeWhere((key, value) => value == null); + queryParams.removeWhere((key, dynamic value) => value == null); + headerParams.removeWhere((key, dynamic value) => value == null); - final List contentTypes = [ + final contentTypes = [ 'application/json', ]; - final serializedBody = _serializers.serialize(user); + final bodySerializer = _serializers.serializerForType(User) as Serializer; + final serializedBody = _serializers.serializeWith(bodySerializer, user); final jsonuser = json.encode(serializedBody); bodyData = jsonuser; - return _dio.request( + return _dio.request( _path, queryParameters: queryParams, data: bodyData, options: Options( method: 'put'.toUpperCase(), headers: headerParams, - extra: { - 'secure': [], + extra: { + 'secure': >[], if (extra != null) ...extra, }, validateStatus: validateStatus, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api_util.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api_util.dart index e99530f6c39..361fab65af5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api_util.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api_util.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:convert'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/api_key_auth.dart index 6cde089a9a1..76c1fc890c8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/api_key_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class ApiKeyAuthInterceptor extends AuthInterceptor { Map apiKeys = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "apiKey"); - for (var info in authInfo) { - final authName = info["name"]; - final authKeyName = info["keyName"]; - final authWhere = info["where"]; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; final apiKey = apiKeys[authName]; if (apiKey != null) { if (authWhere == 'query') { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/auth.dart index 703127c762b..1cca446ee78 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/auth.dart @@ -1,4 +1,9 @@ -import 'dart:async'; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import import 'package:dio/dio.dart'; @@ -8,11 +13,11 @@ abstract class AuthInterceptor extends Interceptor { * Can return null if type is not present on auth data or if route doesn't need authentication */ List> getAuthInfo(RequestOptions route, String type) { - if (route.extra.containsKey("secure")) { - final auth = route.extra["secure"]; - List> results = []; - for (var info in auth) { - if(info["type"] == type) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + final results = >[]; + for (final info in auth) { + if (info['type'] == type) { results.add(info); } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/basic_auth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/basic_auth.dart index 14334a2d288..1f9a2e281f5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/basic_auth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/basic_auth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'dart:convert'; import 'package:openapi/auth/auth.dart'; @@ -14,13 +21,13 @@ class BasicAuthInterceptor extends AuthInterceptor { Map authInfo = {}; @override - Future onRequest(RequestOptions options) { + Future onRequest(RequestOptions options) { final metadataAuthInfo = getAuthInfo(options, 'basic'); - for (var info in metadataAuthInfo) { - final authName = info['name']; + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; final basicAuthInfo = authInfo[authName]; - if(basicAuthInfo != null) { - String basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); + if (basicAuthInfo != null) { + final basicAuth = 'Basic ' + base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}')); options.headers['Authorization'] = basicAuth; break; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/oauth.dart index 3fb06b580b9..481447bffdf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/auth/oauth.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:async'; import 'package:openapi/auth/auth.dart'; import 'package:dio/dio.dart'; @@ -6,12 +13,12 @@ class OAuthInterceptor extends AuthInterceptor { Map tokens = {}; @override - Future onRequest(RequestOptions options) { - final authInfo = getAuthInfo(options, "oauth"); - for (var info in authInfo) { - final token = tokens[info["name"]]; - if(token != null) { - options.headers["Authorization"] = "Bearer ${token}"; + Future onRequest(RequestOptions options) { + final authInfo = getAuthInfo(options, 'oauth'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; break; } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/additional_properties_class.dart index 231d14a7307..c45491b84ba 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/additional_properties_class.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -19,7 +26,7 @@ abstract class AdditionalPropertiesClass implements Built b; - factory AdditionalPropertiesClass([updates(AdditionalPropertiesClassBuilder b)]) = _$AdditionalPropertiesClass; + factory AdditionalPropertiesClass([void updates(AdditionalPropertiesClassBuilder b)]) = _$AdditionalPropertiesClass; static Serializer get serializer => _$additionalPropertiesClassSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/animal.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/animal.dart index 9c95b826bcc..ffbfe2ab5d6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/animal.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -19,7 +26,7 @@ abstract class Animal implements Built { static void _initializeBuilder(AnimalBuilder b) => b ..color = 'red'; - factory Animal([updates(AnimalBuilder b)]) = _$Animal; + factory Animal([void updates(AnimalBuilder b)]) = _$Animal; static Serializer get serializer => _$animalSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/api_response.dart index 137b6de21ab..c5bc1e59646 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/api_response.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -22,7 +29,7 @@ abstract class ApiResponse implements Built { static void _initializeBuilder(ApiResponseBuilder b) => b; - factory ApiResponse([updates(ApiResponseBuilder b)]) = _$ApiResponse; + factory ApiResponse([void updates(ApiResponseBuilder b)]) = _$ApiResponse; static Serializer get serializer => _$apiResponseSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart index d2700a8356f..4345860869a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,7 +22,7 @@ abstract class ArrayOfArrayOfNumberOnly implements Built b; - factory ArrayOfArrayOfNumberOnly([updates(ArrayOfArrayOfNumberOnlyBuilder b)]) = _$ArrayOfArrayOfNumberOnly; + factory ArrayOfArrayOfNumberOnly([void updates(ArrayOfArrayOfNumberOnlyBuilder b)]) = _$ArrayOfArrayOfNumberOnly; static Serializer get serializer => _$arrayOfArrayOfNumberOnlySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_number_only.dart index 86f09a92bd6..6198926fae6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_of_number_only.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,7 +22,7 @@ abstract class ArrayOfNumberOnly implements Built b; - factory ArrayOfNumberOnly([updates(ArrayOfNumberOnlyBuilder b)]) = _$ArrayOfNumberOnly; + factory ArrayOfNumberOnly([void updates(ArrayOfNumberOnlyBuilder b)]) = _$ArrayOfNumberOnly; static Serializer get serializer => _$arrayOfNumberOnlySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_test.dart index cb602702bb9..9aa9ea6d18c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/array_test.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:openapi/model/read_only_first.dart'; import 'package:built_value/built_value.dart'; @@ -24,7 +31,7 @@ abstract class ArrayTest implements Built { static void _initializeBuilder(ArrayTestBuilder b) => b; - factory ArrayTest([updates(ArrayTestBuilder b)]) = _$ArrayTest; + factory ArrayTest([void updates(ArrayTestBuilder b)]) = _$ArrayTest; static Serializer get serializer => _$arrayTestSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/capitalization.dart index 41364d53b56..ba0c23da73a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/capitalization.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -35,7 +42,7 @@ abstract class Capitalization implements Built b; - factory Capitalization([updates(CapitalizationBuilder b)]) = _$Capitalization; + factory Capitalization([void updates(CapitalizationBuilder b)]) = _$Capitalization; static Serializer get serializer => _$capitalizationSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat.dart index 946f3353413..2fe5aa122ff 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/animal.dart'; import 'package:openapi/model/cat_all_of.dart'; import 'package:built_value/built_value.dart'; @@ -25,7 +32,7 @@ abstract class Cat implements Built { static void _initializeBuilder(CatBuilder b) => b ..color = 'red'; - factory Cat([updates(CatBuilder b)]) = _$Cat; + factory Cat([void updates(CatBuilder b)]) = _$Cat; static Serializer get serializer => _$catSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat_all_of.dart index 67961695b26..b839a19cf09 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/cat_all_of.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class CatAllOf implements Built { static void _initializeBuilder(CatAllOfBuilder b) => b; - factory CatAllOf([updates(CatAllOfBuilder b)]) = _$CatAllOf; + factory CatAllOf([void updates(CatAllOfBuilder b)]) = _$CatAllOf; static Serializer get serializer => _$catAllOfSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/category.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/category.dart index 0a46032028a..559aaea651a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/category.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -19,7 +26,7 @@ abstract class Category implements Built { static void _initializeBuilder(CategoryBuilder b) => b ..name = 'default-name'; - factory Category([updates(CategoryBuilder b)]) = _$Category; + factory Category([void updates(CategoryBuilder b)]) = _$Category; static Serializer get serializer => _$categorySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/class_model.dart index f46cf38c5c4..2c32de103b9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/class_model.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class ClassModel implements Built { static void _initializeBuilder(ClassModelBuilder b) => b; - factory ClassModel([updates(ClassModelBuilder b)]) = _$ClassModel; + factory ClassModel([void updates(ClassModelBuilder b)]) = _$ClassModel; static Serializer get serializer => _$classModelSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog.dart index 0914e416ce3..443ce5d74a5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/animal.dart'; import 'package:openapi/model/dog_all_of.dart'; import 'package:built_value/built_value.dart'; @@ -25,7 +32,7 @@ abstract class Dog implements Built { static void _initializeBuilder(DogBuilder b) => b ..color = 'red'; - factory Dog([updates(DogBuilder b)]) = _$Dog; + factory Dog([void updates(DogBuilder b)]) = _$Dog; static Serializer get serializer => _$dogSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog_all_of.dart index 5805cdd29ce..7a0fba00849 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/dog_all_of.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class DogAllOf implements Built { static void _initializeBuilder(DogAllOfBuilder b) => b; - factory DogAllOf([updates(DogAllOfBuilder b)]) = _$DogAllOf; + factory DogAllOf([void updates(DogAllOfBuilder b)]) = _$DogAllOf; static Serializer get serializer => _$dogAllOfSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_arrays.dart index 6abf34bc4a2..7823f0163dc 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_arrays.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -21,7 +28,7 @@ abstract class EnumArrays implements Built { static void _initializeBuilder(EnumArraysBuilder b) => b; - factory EnumArrays([updates(EnumArraysBuilder b)]) = _$EnumArrays; + factory EnumArrays([void updates(EnumArraysBuilder b)]) = _$EnumArrays; static Serializer get serializer => _$enumArraysSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_test.dart index 4c48f04f8a5..e2fee623427 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/enum_test.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/outer_enum_integer_default_value.dart'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/model/outer_enum_default_value.dart'; @@ -55,7 +62,7 @@ abstract class EnumTest implements Built { static void _initializeBuilder(EnumTestBuilder b) => b; - factory EnumTest([updates(EnumTestBuilder b)]) = _$EnumTest; + factory EnumTest([void updates(EnumTestBuilder b)]) = _$EnumTest; static Serializer get serializer => _$enumTestSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/file_schema_test_class.dart index fccb6c1708d..1bcfce7e9cf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/file_schema_test_class.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/model_file.dart'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; @@ -20,7 +27,7 @@ abstract class FileSchemaTestClass implements Built b; - factory FileSchemaTestClass([updates(FileSchemaTestClassBuilder b)]) = _$FileSchemaTestClass; + factory FileSchemaTestClass([void updates(FileSchemaTestClassBuilder b)]) = _$FileSchemaTestClass; static Serializer get serializer => _$fileSchemaTestClassSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/foo.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/foo.dart index 3e2020ea2ef..9984cc16f58 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/foo.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,7 +22,7 @@ abstract class Foo implements Built { static void _initializeBuilder(FooBuilder b) => b ..bar = 'bar'; - factory Foo([updates(FooBuilder b)]) = _$Foo; + factory Foo([void updates(FooBuilder b)]) = _$Foo; static Serializer get serializer => _$fooSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/format_test.dart index 9738eb3de68..8a2898740a5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/format_test.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'dart:typed_data'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -77,7 +84,7 @@ abstract class FormatTest implements Built { static void _initializeBuilder(FormatTestBuilder b) => b; - factory FormatTest([updates(FormatTestBuilder b)]) = _$FormatTest; + factory FormatTest([void updates(FormatTestBuilder b)]) = _$FormatTest; static Serializer get serializer => _$formatTestSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/has_only_read_only.dart index 9489432fe52..9c5eb2686cb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/has_only_read_only.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class HasOnlyReadOnly implements Built b; - factory HasOnlyReadOnly([updates(HasOnlyReadOnlyBuilder b)]) = _$HasOnlyReadOnly; + factory HasOnlyReadOnly([void updates(HasOnlyReadOnlyBuilder b)]) = _$HasOnlyReadOnly; static Serializer get serializer => _$hasOnlyReadOnlySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/health_check_result.dart index dd6c1ccaff7..848806a19b5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/health_check_result.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class HealthCheckResult implements Built b; - factory HealthCheckResult([updates(HealthCheckResultBuilder b)]) = _$HealthCheckResult; + factory HealthCheckResult([void updates(HealthCheckResultBuilder b)]) = _$HealthCheckResult; static Serializer get serializer => _$healthCheckResultSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object.dart deleted file mode 100644 index b1477f60e8c..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object.g.dart'; - -abstract class InlineObject implements Built { - - /// Updated name of the pet - @nullable - @BuiltValueField(wireName: r'name') - String get name; - - /// Updated status of the pet - @nullable - @BuiltValueField(wireName: r'status') - String get status; - - // Boilerplate code needed to wire-up generated code - InlineObject._(); - - static void _initializeBuilder(InlineObjectBuilder b) => b; - - factory InlineObject([updates(InlineObjectBuilder b)]) = _$InlineObject; - static Serializer get serializer => _$inlineObjectSerializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object1.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object1.dart deleted file mode 100644 index 2eadc367d2d..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object1.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:typed_data'; -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object1.g.dart'; - -abstract class InlineObject1 implements Built { - - /// Additional data to pass to server - @nullable - @BuiltValueField(wireName: r'additionalMetadata') - String get additionalMetadata; - - /// file to upload - @nullable - @BuiltValueField(wireName: r'file') - Uint8List get file; - - // Boilerplate code needed to wire-up generated code - InlineObject1._(); - - static void _initializeBuilder(InlineObject1Builder b) => b; - - factory InlineObject1([updates(InlineObject1Builder b)]) = _$InlineObject1; - static Serializer get serializer => _$inlineObject1Serializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object2.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object2.dart deleted file mode 100644 index 833fef79291..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object2.dart +++ /dev/null @@ -1,65 +0,0 @@ -import 'package:built_collection/built_collection.dart'; -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object2.g.dart'; - -abstract class InlineObject2 implements Built { - - /// Form parameter enum test (string array) - @nullable - @BuiltValueField(wireName: r'enum_form_string_array') - BuiltList get enumFormStringArray; - // enum enumFormStringArrayEnum { >, $, }; - - /// Form parameter enum test (string) - @nullable - @BuiltValueField(wireName: r'enum_form_string') - InlineObject2EnumFormStringEnum get enumFormString; - // enum enumFormStringEnum { _abc, -efg, (xyz), }; - - // Boilerplate code needed to wire-up generated code - InlineObject2._(); - - static void _initializeBuilder(InlineObject2Builder b) => b - ..enumFormString = const InlineObject2EnumFormStringEnum._('-efg'); - - factory InlineObject2([updates(InlineObject2Builder b)]) = _$InlineObject2; - static Serializer get serializer => _$inlineObject2Serializer; -} - -class InlineObject2EnumFormStringArrayEnum extends EnumClass { - - @BuiltValueEnumConst(wireName: r'>') - static const InlineObject2EnumFormStringArrayEnum greaterThan = _$inlineObject2EnumFormStringArrayEnum_greaterThan; - @BuiltValueEnumConst(wireName: r'\$') - static const InlineObject2EnumFormStringArrayEnum dollar = _$inlineObject2EnumFormStringArrayEnum_dollar; - - static Serializer get serializer => _$inlineObject2EnumFormStringArrayEnumSerializer; - - const InlineObject2EnumFormStringArrayEnum._(String name): super(name); - - static BuiltSet get values => _$inlineObject2EnumFormStringArrayEnumValues; - static InlineObject2EnumFormStringArrayEnum valueOf(String name) => _$inlineObject2EnumFormStringArrayEnumValueOf(name); -} - -class InlineObject2EnumFormStringEnum extends EnumClass { - - /// Form parameter enum test (string) - @BuiltValueEnumConst(wireName: r'_abc') - static const InlineObject2EnumFormStringEnum abc = _$inlineObject2EnumFormStringEnum_abc; - /// Form parameter enum test (string) - @BuiltValueEnumConst(wireName: r'-efg') - static const InlineObject2EnumFormStringEnum efg = _$inlineObject2EnumFormStringEnum_efg; - /// Form parameter enum test (string) - @BuiltValueEnumConst(wireName: r'(xyz)') - static const InlineObject2EnumFormStringEnum leftParenthesisXyzRightParenthesis = _$inlineObject2EnumFormStringEnum_leftParenthesisXyzRightParenthesis; - - static Serializer get serializer => _$inlineObject2EnumFormStringEnumSerializer; - - const InlineObject2EnumFormStringEnum._(String name): super(name); - - static BuiltSet get values => _$inlineObject2EnumFormStringEnumValues; - static InlineObject2EnumFormStringEnum valueOf(String name) => _$inlineObject2EnumFormStringEnumValueOf(name); -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object3.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object3.dart deleted file mode 100644 index 6afbdfa1625..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object3.dart +++ /dev/null @@ -1,87 +0,0 @@ -import 'dart:typed_data'; -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object3.g.dart'; - -abstract class InlineObject3 implements Built { - - /// None - @nullable - @BuiltValueField(wireName: r'integer') - int get integer; - - /// None - @nullable - @BuiltValueField(wireName: r'int32') - int get int32; - - /// None - @nullable - @BuiltValueField(wireName: r'int64') - int get int64; - - /// None - @nullable - @BuiltValueField(wireName: r'number') - num get number; - - /// None - @nullable - @BuiltValueField(wireName: r'float') - double get float; - - /// None - @nullable - @BuiltValueField(wireName: r'double') - double get double_; - - /// None - @nullable - @BuiltValueField(wireName: r'string') - String get string; - - /// None - @nullable - @BuiltValueField(wireName: r'pattern_without_delimiter') - String get patternWithoutDelimiter; - - /// None - @nullable - @BuiltValueField(wireName: r'byte') - String get byte; - - /// None - @nullable - @BuiltValueField(wireName: r'binary') - Uint8List get binary; - - /// None - @nullable - @BuiltValueField(wireName: r'date') - DateTime get date; - - /// None - @nullable - @BuiltValueField(wireName: r'dateTime') - DateTime get dateTime; - - /// None - @nullable - @BuiltValueField(wireName: r'password') - String get password; - - /// None - @nullable - @BuiltValueField(wireName: r'callback') - String get callback; - - // Boilerplate code needed to wire-up generated code - InlineObject3._(); - - static void _initializeBuilder(InlineObject3Builder b) => b; - - factory InlineObject3([updates(InlineObject3Builder b)]) = _$InlineObject3; - static Serializer get serializer => _$inlineObject3Serializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object4.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object4.dart deleted file mode 100644 index 212de4d90dd..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object4.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object4.g.dart'; - -abstract class InlineObject4 implements Built { - - /// field1 - @nullable - @BuiltValueField(wireName: r'param') - String get param; - - /// field2 - @nullable - @BuiltValueField(wireName: r'param2') - String get param2; - - // Boilerplate code needed to wire-up generated code - InlineObject4._(); - - static void _initializeBuilder(InlineObject4Builder b) => b; - - factory InlineObject4([updates(InlineObject4Builder b)]) = _$InlineObject4; - static Serializer get serializer => _$inlineObject4Serializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object5.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object5.dart deleted file mode 100644 index b212a41cc6c..00000000000 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_object5.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:typed_data'; -import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; - -part 'inline_object5.g.dart'; - -abstract class InlineObject5 implements Built { - - /// Additional data to pass to server - @nullable - @BuiltValueField(wireName: r'additionalMetadata') - String get additionalMetadata; - - /// file to upload - @nullable - @BuiltValueField(wireName: r'requiredFile') - Uint8List get requiredFile; - - // Boilerplate code needed to wire-up generated code - InlineObject5._(); - - static void _initializeBuilder(InlineObject5Builder b) => b; - - factory InlineObject5([updates(InlineObject5Builder b)]) = _$InlineObject5; - static Serializer get serializer => _$inlineObject5Serializer; -} - diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_response_default.dart index ba9c7ad34f6..b82e139b7c1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/inline_response_default.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/foo.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,7 +22,7 @@ abstract class InlineResponseDefault implements Built b; - factory InlineResponseDefault([updates(InlineResponseDefaultBuilder b)]) = _$InlineResponseDefault; + factory InlineResponseDefault([void updates(InlineResponseDefaultBuilder b)]) = _$InlineResponseDefault; static Serializer get serializer => _$inlineResponseDefaultSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/map_test.dart index 39dca4c8bba..c8f311d81d6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/map_test.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -28,7 +35,7 @@ abstract class MapTest implements Built { static void _initializeBuilder(MapTestBuilder b) => b; - factory MapTest([updates(MapTestBuilder b)]) = _$MapTest; + factory MapTest([void updates(MapTestBuilder b)]) = _$MapTest; static Serializer get serializer => _$mapTestSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart index 19b4b3aa521..31be421309c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/animal.dart'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; @@ -24,7 +31,7 @@ abstract class MixedPropertiesAndAdditionalPropertiesClass implements Built b; - factory MixedPropertiesAndAdditionalPropertiesClass([updates(MixedPropertiesAndAdditionalPropertiesClassBuilder b)]) = _$MixedPropertiesAndAdditionalPropertiesClass; + factory MixedPropertiesAndAdditionalPropertiesClass([void updates(MixedPropertiesAndAdditionalPropertiesClassBuilder b)]) = _$MixedPropertiesAndAdditionalPropertiesClass; static Serializer get serializer => _$mixedPropertiesAndAdditionalPropertiesClassSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model200_response.dart index 1f8ea361b90..5dafab90e8a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model200_response.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Model200Response implements Built b; - factory Model200Response([updates(Model200ResponseBuilder b)]) = _$Model200Response; + factory Model200Response([void updates(Model200ResponseBuilder b)]) = _$Model200Response; static Serializer get serializer => _$model200ResponseSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_client.dart index 2ee3e1ced2c..5a99a70d9af 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_client.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class ModelClient implements Built { static void _initializeBuilder(ModelClientBuilder b) => b; - factory ModelClient([updates(ModelClientBuilder b)]) = _$ModelClient; + factory ModelClient([void updates(ModelClientBuilder b)]) = _$ModelClient; static Serializer get serializer => _$modelClientSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_enum_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_enum_class.dart index 0877d459f7a..0a158ee5893 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_enum_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_enum_class.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_file.dart index bc1e736feca..07474a9cc61 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_file.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,7 +22,7 @@ abstract class ModelFile implements Built { static void _initializeBuilder(ModelFileBuilder b) => b; - factory ModelFile([updates(ModelFileBuilder b)]) = _$ModelFile; + factory ModelFile([void updates(ModelFileBuilder b)]) = _$ModelFile; static Serializer get serializer => _$modelFileSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_list.dart index e95e59d4ec7..464a9e6baec 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_list.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class ModelList implements Built { static void _initializeBuilder(ModelListBuilder b) => b; - factory ModelList([updates(ModelListBuilder b)]) = _$ModelList; + factory ModelList([void updates(ModelListBuilder b)]) = _$ModelList; static Serializer get serializer => _$modelListSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_return.dart index 9d297a1538b..31259ba2086 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/model_return.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class ModelReturn implements Built { static void _initializeBuilder(ModelReturnBuilder b) => b; - factory ModelReturn([updates(ModelReturnBuilder b)]) = _$ModelReturn; + factory ModelReturn([void updates(ModelReturnBuilder b)]) = _$ModelReturn; static Serializer get serializer => _$modelReturnSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/name.dart index abd03a16c05..e84fe0359d9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/name.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -26,7 +33,7 @@ abstract class Name implements Built { static void _initializeBuilder(NameBuilder b) => b; - factory Name([updates(NameBuilder b)]) = _$Name; + factory Name([void updates(NameBuilder b)]) = _$Name; static Serializer get serializer => _$nameSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/nullable_class.dart index 33e36a0aacf..8306d9546bb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/nullable_class.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/built_value.dart'; @@ -60,7 +67,7 @@ abstract class NullableClass implements Built b; - factory NullableClass([updates(NullableClassBuilder b)]) = _$NullableClass; + factory NullableClass([void updates(NullableClassBuilder b)]) = _$NullableClass; static Serializer get serializer => _$nullableClassSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/number_only.dart index 0f801275141..839165bb796 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/number_only.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class NumberOnly implements Built { static void _initializeBuilder(NumberOnlyBuilder b) => b; - factory NumberOnly([updates(NumberOnlyBuilder b)]) = _$NumberOnly; + factory NumberOnly([void updates(NumberOnlyBuilder b)]) = _$NumberOnly; static Serializer get serializer => _$numberOnlySerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/order.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/order.dart index 517fba8eb73..f26c6213820 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/order.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -38,7 +45,7 @@ abstract class Order implements Built { static void _initializeBuilder(OrderBuilder b) => b ..complete = false; - factory Order([updates(OrderBuilder b)]) = _$Order; + factory Order([void updates(OrderBuilder b)]) = _$Order; static Serializer get serializer => _$orderSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_composite.dart index 3c2c45170aa..bc748ef970f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_composite.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -22,7 +29,7 @@ abstract class OuterComposite implements Built b; - factory OuterComposite([updates(OuterCompositeBuilder b)]) = _$OuterComposite; + factory OuterComposite([void updates(OuterCompositeBuilder b)]) = _$OuterComposite; static Serializer get serializer => _$outerCompositeSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum.dart index 0409dc50666..ea68739f319 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart index 1ba37949551..1751e9e4396 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer.dart index 83db130592b..8519a117116 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart index 7eaeba5dfc2..cfc1b18f26b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/pet.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/pet.dart index 1fb992db794..98757f5e7ce 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/pet.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:openapi/model/tag.dart'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/model/category.dart'; @@ -39,7 +46,7 @@ abstract class Pet implements Built { static void _initializeBuilder(PetBuilder b) => b; - factory Pet([updates(PetBuilder b)]) = _$Pet; + factory Pet([void updates(PetBuilder b)]) = _$Pet; static Serializer get serializer => _$petSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/read_only_first.dart index 898c30f40e1..6ac8f07169c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/read_only_first.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class ReadOnlyFirst implements Built b; - factory ReadOnlyFirst([updates(ReadOnlyFirstBuilder b)]) = _$ReadOnlyFirst; + factory ReadOnlyFirst([void updates(ReadOnlyFirstBuilder b)]) = _$ReadOnlyFirst; static Serializer get serializer => _$readOnlyFirstSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/special_model_name.dart index f80fcb16f66..dc072d5ddab 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/special_model_name.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,7 +21,7 @@ abstract class SpecialModelName implements Built b; - factory SpecialModelName([updates(SpecialModelNameBuilder b)]) = _$SpecialModelName; + factory SpecialModelName([void updates(SpecialModelNameBuilder b)]) = _$SpecialModelName; static Serializer get serializer => _$specialModelNameSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/tag.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/tag.dart index 8149a7d3498..528acd843e7 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/tag.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,7 +25,7 @@ abstract class Tag implements Built { static void _initializeBuilder(TagBuilder b) => b; - factory Tag([updates(TagBuilder b)]) = _$Tag; + factory Tag([void updates(TagBuilder b)]) = _$Tag; static Serializer get serializer => _$tagSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/user.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/user.dart index 3fd4092d546..93259a43019 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/model/user.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -43,7 +50,7 @@ abstract class User implements Built { static void _initializeBuilder(UserBuilder b) => b; - factory User([updates(UserBuilder b)]) = _$User; + factory User([void updates(UserBuilder b)]) = _$User; static Serializer get serializer => _$userSerializer; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/serializers.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/serializers.dart index 833c5800619..93a24c5a7d2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/serializers.dart @@ -1,3 +1,10 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.6 + +// ignore_for_file: unused_import + library serializers; import 'package:built_value/iso_8601_date_time_serializer.dart'; @@ -50,191 +57,72 @@ import 'package:openapi/model/special_model_name.dart'; import 'package:openapi/model/tag.dart'; import 'package:openapi/model/user.dart'; - part 'serializers.g.dart'; @SerializersFor(const [ -AdditionalPropertiesClass, -Animal, -ApiResponse, -ArrayOfArrayOfNumberOnly, -ArrayOfNumberOnly, -ArrayTest, -Capitalization, -Cat, -CatAllOf, -Category, -ClassModel, -Dog, -DogAllOf, -EnumArrays, -EnumTest, -FileSchemaTestClass, -Foo, -FormatTest, -HasOnlyReadOnly, -HealthCheckResult, -InlineResponseDefault, -MapTest, -MixedPropertiesAndAdditionalPropertiesClass, -Model200Response, -ModelClient, -ModelEnumClass, -ModelFile, -ModelList, -ModelReturn, -Name, -NullableClass, -NumberOnly, -Order, -OuterComposite, -OuterEnum, -OuterEnumDefaultValue, -OuterEnumInteger, -OuterEnumIntegerDefaultValue, -Pet, -ReadOnlyFirst, -SpecialModelName, -Tag, -User, - + AdditionalPropertiesClass, + Animal, + ApiResponse, + ArrayOfArrayOfNumberOnly, + ArrayOfNumberOnly, + ArrayTest, + Capitalization, + Cat, + CatAllOf, + Category, + ClassModel, + Dog, + DogAllOf, + EnumArrays, + EnumTest, + FileSchemaTestClass, + Foo, + FormatTest, + HasOnlyReadOnly, + HealthCheckResult, + InlineResponseDefault, + MapTest, + MixedPropertiesAndAdditionalPropertiesClass, + Model200Response, + ModelClient, + ModelEnumClass, + ModelFile, + ModelList, + ModelReturn, + Name, + NullableClass, + NumberOnly, + Order, + OuterComposite, + OuterEnum, + OuterEnumDefaultValue, + OuterEnumInteger, + OuterEnumIntegerDefaultValue, + Pet, + ReadOnlyFirst, + SpecialModelName, + Tag, + User, ]) - -//allow all models to be serialized within a list Serializers serializers = (_$serializers.toBuilder() -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(AdditionalPropertiesClass)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Animal)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ApiResponse)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ArrayOfArrayOfNumberOnly)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ArrayOfNumberOnly)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ArrayTest)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Capitalization)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Cat)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(CatAllOf)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Category)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ClassModel)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Dog)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(DogAllOf)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(EnumArrays)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(EnumTest)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(FileSchemaTestClass)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Foo)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(FormatTest)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(HasOnlyReadOnly)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(HealthCheckResult)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(InlineResponseDefault)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(MapTest)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(MixedPropertiesAndAdditionalPropertiesClass)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Model200Response)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ModelClient)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ModelEnumClass)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ModelFile)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ModelList)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ModelReturn)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Name)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(NullableClass)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(NumberOnly)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Order)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(OuterComposite)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(OuterEnum)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(OuterEnumDefaultValue)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(OuterEnumInteger)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(OuterEnumIntegerDefaultValue)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Pet)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(ReadOnlyFirst)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(SpecialModelName)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(Tag)]), -() => new ListBuilder()) -..addBuilderFactory( -const FullType(BuiltList, const [const FullType(User)]), -() => new ListBuilder()) - -..add(Iso8601DateTimeSerializer()) -).build(); + ..addBuilderFactory( + const FullType(BuiltMap, [FullType(String), FullType(String)]), + () => MapBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltList, [FullType(Pet)]), + () => ListBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltMap, [FullType(String), FullType(int)]), + () => MapBuilder(), + ) + ..addBuilderFactory( + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), + ) + ..add(Iso8601DateTimeSerializer())) + .build(); Serializers standardSerializers = -(serializers.toBuilder() -..addPlugin(StandardJsonPlugin())).build(); + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pom.xml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pom.xml index a37f8b9b5e3..6b98636b6a6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pom.xml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pom.xml @@ -67,6 +67,22 @@ + + dartanalyzer + integration-test + + exec + + + dartanalyzer + + --fatal-infos + --options + analysis_options.yaml + . + + + pub-test integration-test diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml index 20b190aa1d3..c7c5c5aec83 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml @@ -2,7 +2,7 @@ name: openapi version: 1.0.0 description: OpenAPI API client environment: - sdk: ">=2.3.0 <3.0.0" + sdk: ">=2.6.0 <3.0.0" dependencies: dio: ^3.0.9 built_value: ^7.1.0 diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/additional_properties_class_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/additional_properties_class_test.dart index cf1888a7461..81db250160d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/additional_properties_class_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/additional_properties_class_test.dart @@ -6,12 +6,12 @@ void main() { final instance = AdditionalPropertiesClass(); group(AdditionalPropertiesClass, () { - // BuiltMap mapProperty (default value: const {}) + // BuiltMap mapProperty test('to test the property `mapProperty`', () async { // TODO }); - // BuiltMap> mapOfMapProperty (default value: const {}) + // BuiltMap> mapOfMapProperty test('to test the property `mapOfMapProperty`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart index bae2d856b6c..d1fd66cefbe 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart @@ -6,7 +6,7 @@ void main() { final instance = Animal(); group(Animal, () { - // String className (default value: null) + // String className test('to test the property `className`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/another_fake_api_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/another_fake_api_test.dart index af0d198a0b6..e302c7b0e50 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/another_fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/another_fake_api_test.dart @@ -12,7 +12,7 @@ void main() { // // To test special tags and operation ID starting with number // - //Future call123testSpecialTags(Client client) async + //Future call123testSpecialTags(ModelClient modelClient) async test('test call123testSpecialTags', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/api_response_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/api_response_test.dart index d80b2976160..39d3ffc2941 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/api_response_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/api_response_test.dart @@ -6,17 +6,17 @@ void main() { final instance = ApiResponse(); group(ApiResponse, () { - // int code (default value: null) + // int code test('to test the property `code`', () async { // TODO }); - // String type (default value: null) + // String type test('to test the property `type`', () async { // TODO }); - // String message (default value: null) + // String message test('to test the property `message`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart index e7384400a22..6d4f7c31fde 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ArrayOfArrayOfNumberOnly(); group(ArrayOfArrayOfNumberOnly, () { - // BuiltList> arrayArrayNumber (default value: const []) + // BuiltList> arrayArrayNumber test('to test the property `arrayArrayNumber`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_number_only_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_number_only_test.dart index f40a137a8d2..4a34a792ec3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_number_only_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_of_number_only_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ArrayOfNumberOnly(); group(ArrayOfNumberOnly, () { - // BuiltList arrayNumber (default value: const []) + // BuiltList arrayNumber test('to test the property `arrayNumber`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_test_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_test_test.dart index f8059a850cc..0c53feccd9a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_test_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/array_test_test.dart @@ -6,17 +6,17 @@ void main() { final instance = ArrayTest(); group(ArrayTest, () { - // BuiltList arrayOfString (default value: const []) + // BuiltList arrayOfString test('to test the property `arrayOfString`', () async { // TODO }); - // BuiltList> arrayArrayOfInteger (default value: const []) + // BuiltList> arrayArrayOfInteger test('to test the property `arrayArrayOfInteger`', () async { // TODO }); - // BuiltList> arrayArrayOfModel (default value: const []) + // BuiltList> arrayArrayOfModel test('to test the property `arrayArrayOfModel`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/capitalization_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/capitalization_test.dart index 304df4d82af..0775e8d2756 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/capitalization_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/capitalization_test.dart @@ -6,33 +6,33 @@ void main() { final instance = Capitalization(); group(Capitalization, () { - // String smallCamel (default value: null) + // String smallCamel test('to test the property `smallCamel`', () async { // TODO }); - // String capitalCamel (default value: null) + // String capitalCamel test('to test the property `capitalCamel`', () async { // TODO }); - // String smallSnake (default value: null) + // String smallSnake test('to test the property `smallSnake`', () async { // TODO }); - // String capitalSnake (default value: null) + // String capitalSnake test('to test the property `capitalSnake`', () async { // TODO }); - // String sCAETHFlowPoints (default value: null) + // String sCAETHFlowPoints test('to test the property `sCAETHFlowPoints`', () async { // TODO }); // Name of the pet - // String ATT_NAME (default value: null) + // String ATT_NAME test('to test the property `ATT_NAME`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart index b8e84359a30..460577b0234 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart @@ -6,7 +6,7 @@ void main() { final instance = CatAllOf(); group(CatAllOf, () { - // bool declawed (default value: null) + // bool declawed test('to test the property `declawed`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_test.dart index a066e555492..05c2b79badb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_test.dart @@ -6,7 +6,7 @@ void main() { final instance = Cat(); group(Cat, () { - // String className (default value: null) + // String className test('to test the property `className`', () async { // TODO }); @@ -16,7 +16,7 @@ void main() { // TODO }); - // bool declawed (default value: null) + // bool declawed test('to test the property `declawed`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/category_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/category_test.dart index 4ef34fea723..fc2c1ecb46e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/category_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/category_test.dart @@ -6,7 +6,7 @@ void main() { final instance = Category(); group(Category, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart index d8daf6f70dd..af5ab7492c7 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ClassModel(); group(ClassModel, () { - // String class_ (default value: null) + // String class_ test('to test the property `class_`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart index 4f208c95b6f..f7bed7fdebf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart @@ -6,7 +6,7 @@ void main() { final instance = DogAllOf(); group(DogAllOf, () { - // String breed (default value: null) + // String breed test('to test the property `breed`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_test.dart index 6042386f178..4daa11323da 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_test.dart @@ -6,7 +6,7 @@ void main() { final instance = Dog(); group(Dog, () { - // String className (default value: null) + // String className test('to test the property `className`', () async { // TODO }); @@ -16,7 +16,7 @@ void main() { // TODO }); - // String breed (default value: null) + // String breed test('to test the property `breed`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_arrays_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_arrays_test.dart index 5c8b0da4c05..3aa0e621f79 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_arrays_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_arrays_test.dart @@ -6,12 +6,12 @@ void main() { final instance = EnumArrays(); group(EnumArrays, () { - // String justSymbol (default value: null) + // String justSymbol test('to test the property `justSymbol`', () async { // TODO }); - // BuiltList arrayEnum (default value: const []) + // BuiltList arrayEnum test('to test the property `arrayEnum`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_test_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_test_test.dart index 3565cb937a0..8d963d1eead 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_test_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/enum_test_test.dart @@ -6,42 +6,42 @@ void main() { final instance = EnumTest(); group(EnumTest, () { - // String enumString (default value: null) + // String enumString test('to test the property `enumString`', () async { // TODO }); - // String enumStringRequired (default value: null) + // String enumStringRequired test('to test the property `enumStringRequired`', () async { // TODO }); - // int enumInteger (default value: null) + // int enumInteger test('to test the property `enumInteger`', () async { // TODO }); - // double enumNumber (default value: null) + // double enumNumber test('to test the property `enumNumber`', () async { // TODO }); - // OuterEnum outerEnum (default value: null) + // OuterEnum outerEnum test('to test the property `outerEnum`', () async { // TODO }); - // OuterEnumInteger outerEnumInteger (default value: null) + // OuterEnumInteger outerEnumInteger test('to test the property `outerEnumInteger`', () async { // TODO }); - // OuterEnumDefaultValue outerEnumDefaultValue (default value: null) + // OuterEnumDefaultValue outerEnumDefaultValue test('to test the property `outerEnumDefaultValue`', () async { // TODO }); - // OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue (default value: null) + // OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue test('to test the property `outerEnumIntegerDefaultValue`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_api_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_api_test.dart index 0ffe770cdd4..06ed48d6989 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_api_test.dart @@ -66,7 +66,7 @@ void main() { // // To test \"client\" model // - //Future testClientModel(Client client) async + //Future testClientModel(ModelClient modelClient) async test('test testClientModel', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart index b13dc103ba1..510961f8602 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart @@ -12,7 +12,7 @@ void main() { // // To test class name in snake case // - //Future testClassname(Client client) async + //Future testClassname(ModelClient modelClient) async test('test testClassname', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/file_schema_test_class_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/file_schema_test_class_test.dart index 3dac8bab3af..fcab730f1d5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/file_schema_test_class_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/file_schema_test_class_test.dart @@ -6,12 +6,12 @@ void main() { final instance = FileSchemaTestClass(); group(FileSchemaTestClass, () { - // MultipartFile file (default value: null) + // ModelFile file test('to test the property `file`', () async { // TODO }); - // BuiltList files (default value: const []) + // BuiltList files test('to test the property `files`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/format_test_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/format_test_test.dart index 5630c432b68..1b56b04d4c8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/format_test_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/format_test_test.dart @@ -6,84 +6,84 @@ void main() { final instance = FormatTest(); group(FormatTest, () { - // int integer (default value: null) + // int integer test('to test the property `integer`', () async { // TODO }); - // int int32 (default value: null) + // int int32 test('to test the property `int32`', () async { // TODO }); - // int int64 (default value: null) + // int int64 test('to test the property `int64`', () async { // TODO }); - // num number (default value: null) + // num number test('to test the property `number`', () async { // TODO }); - // double float (default value: null) + // double float test('to test the property `float`', () async { // TODO }); - // double double_ (default value: null) + // double double_ test('to test the property `double_`', () async { // TODO }); - // double decimal (default value: null) + // double decimal test('to test the property `decimal`', () async { // TODO }); - // String string (default value: null) + // String string test('to test the property `string`', () async { // TODO }); - // String byte (default value: null) + // String byte test('to test the property `byte`', () async { // TODO }); - // Uint8List binary (default value: null) + // Uint8List binary test('to test the property `binary`', () async { // TODO }); - // DateTime date (default value: null) + // DateTime date test('to test the property `date`', () async { // TODO }); - // DateTime dateTime (default value: null) + // DateTime dateTime test('to test the property `dateTime`', () async { // TODO }); - // String uuid (default value: null) + // String uuid test('to test the property `uuid`', () async { // TODO }); - // String password (default value: null) + // String password test('to test the property `password`', () async { // TODO }); // A string that is a 10 digit number. Can have leading zeros. - // String patternWithDigits (default value: null) + // String patternWithDigits test('to test the property `patternWithDigits`', () async { // TODO }); // A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. - // String patternWithDigitsAndDelimiter (default value: null) + // String patternWithDigitsAndDelimiter test('to test the property `patternWithDigitsAndDelimiter`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/has_only_read_only_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/has_only_read_only_test.dart index 4a6bfc857dd..2556caff31f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/has_only_read_only_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/has_only_read_only_test.dart @@ -6,12 +6,12 @@ void main() { final instance = HasOnlyReadOnly(); group(HasOnlyReadOnly, () { - // String bar (default value: null) + // String bar test('to test the property `bar`', () async { // TODO }); - // String foo (default value: null) + // String foo test('to test the property `foo`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/health_check_result_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/health_check_result_test.dart index fb5896b660d..81960b87ce8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/health_check_result_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/health_check_result_test.dart @@ -6,7 +6,7 @@ void main() { final instance = HealthCheckResult(); group(HealthCheckResult, () { - // String nullableMessage (default value: null) + // String nullableMessage test('to test the property `nullableMessage`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/inline_response_default_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/inline_response_default_test.dart index acf32ff97f9..cae92c3385e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/inline_response_default_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/inline_response_default_test.dart @@ -6,7 +6,7 @@ void main() { final instance = InlineResponseDefault(); group(InlineResponseDefault, () { - // Foo string (default value: null) + // Foo string test('to test the property `string`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/map_test_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/map_test_test.dart index 90d2efc8805..ed5f45ce721 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/map_test_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/map_test_test.dart @@ -6,22 +6,22 @@ void main() { final instance = MapTest(); group(MapTest, () { - // BuiltMap> mapMapOfString (default value: const {}) + // BuiltMap> mapMapOfString test('to test the property `mapMapOfString`', () async { // TODO }); - // BuiltMap mapOfEnumString (default value: const {}) + // BuiltMap mapOfEnumString test('to test the property `mapOfEnumString`', () async { // TODO }); - // BuiltMap directMap (default value: const {}) + // BuiltMap directMap test('to test the property `directMap`', () async { // TODO }); - // BuiltMap indirectMap (default value: const {}) + // BuiltMap indirectMap test('to test the property `indirectMap`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart index 5e545881931..cc36b6e7dd3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart @@ -6,17 +6,17 @@ void main() { final instance = MixedPropertiesAndAdditionalPropertiesClass(); group(MixedPropertiesAndAdditionalPropertiesClass, () { - // String uuid (default value: null) + // String uuid test('to test the property `uuid`', () async { // TODO }); - // DateTime dateTime (default value: null) + // DateTime dateTime test('to test the property `dateTime`', () async { // TODO }); - // BuiltMap map (default value: const {}) + // BuiltMap map test('to test the property `map`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart index 8d91a2fb850..6b77b5481b6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart @@ -6,12 +6,12 @@ void main() { final instance = Model200Response(); group(Model200Response, () { - // int name (default value: null) + // int name test('to test the property `name`', () async { // TODO }); - // String class_ (default value: null) + // String class_ test('to test the property `class_`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_client_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_client_test.dart index d428e9ccfe7..c3908d24b92 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_client_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_client_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ModelClient(); group(ModelClient, () { - // String client (default value: null) + // String client test('to test the property `client`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_file_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_file_test.dart index 1a931e285a0..4bf8d1250af 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_file_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_file_test.dart @@ -7,7 +7,7 @@ void main() { group(ModelFile, () { // Test capitalization - // String sourceURI (default value: null) + // String sourceURI test('to test the property `sourceURI`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_list_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_list_test.dart index 4d104ab7edc..03cfd40a8f1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_list_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_list_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ModelList(); group(ModelList, () { - // String n123list (default value: null) + // String n123list test('to test the property `n123list`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_return_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_return_test.dart index 2fc81f4da6c..ac0e3574eab 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_return_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model_return_test.dart @@ -6,7 +6,7 @@ void main() { final instance = ModelReturn(); group(ModelReturn, () { - // int return_ (default value: null) + // int return_ test('to test the property `return_`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/name_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/name_test.dart index cbc273245e9..7f3fa21ef78 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/name_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/name_test.dart @@ -6,22 +6,22 @@ void main() { final instance = Name(); group(Name, () { - // int name (default value: null) + // int name test('to test the property `name`', () async { // TODO }); - // int snakeCase (default value: null) + // int snakeCase test('to test the property `snakeCase`', () async { // TODO }); - // String property (default value: null) + // String property test('to test the property `property`', () async { // TODO }); - // int n123number (default value: null) + // int n123number test('to test the property `n123number`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/nullable_class_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/nullable_class_test.dart index 8452f6d4be4..0bcae3b4e8b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/nullable_class_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/nullable_class_test.dart @@ -6,62 +6,62 @@ void main() { final instance = NullableClass(); group(NullableClass, () { - // int integerProp (default value: null) + // int integerProp test('to test the property `integerProp`', () async { // TODO }); - // num numberProp (default value: null) + // num numberProp test('to test the property `numberProp`', () async { // TODO }); - // bool booleanProp (default value: null) + // bool booleanProp test('to test the property `booleanProp`', () async { // TODO }); - // String stringProp (default value: null) + // String stringProp test('to test the property `stringProp`', () async { // TODO }); - // DateTime dateProp (default value: null) + // DateTime dateProp test('to test the property `dateProp`', () async { // TODO }); - // DateTime datetimeProp (default value: null) + // DateTime datetimeProp test('to test the property `datetimeProp`', () async { // TODO }); - // BuiltList arrayNullableProp (default value: const []) + // BuiltList arrayNullableProp test('to test the property `arrayNullableProp`', () async { // TODO }); - // BuiltList arrayAndItemsNullableProp (default value: const []) + // BuiltList arrayAndItemsNullableProp test('to test the property `arrayAndItemsNullableProp`', () async { // TODO }); - // BuiltList arrayItemsNullable (default value: const []) + // BuiltList arrayItemsNullable test('to test the property `arrayItemsNullable`', () async { // TODO }); - // BuiltMap objectNullableProp (default value: const {}) + // BuiltMap objectNullableProp test('to test the property `objectNullableProp`', () async { // TODO }); - // BuiltMap objectAndItemsNullableProp (default value: const {}) + // BuiltMap objectAndItemsNullableProp test('to test the property `objectAndItemsNullableProp`', () async { // TODO }); - // BuiltMap objectItemsNullable (default value: const {}) + // BuiltMap objectItemsNullable test('to test the property `objectItemsNullable`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/number_only_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/number_only_test.dart index 0b905011687..2630062232e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/number_only_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/number_only_test.dart @@ -6,7 +6,7 @@ void main() { final instance = NumberOnly(); group(NumberOnly, () { - // num justNumber (default value: null) + // num justNumber test('to test the property `justNumber`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/order_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/order_test.dart index ea9ac6e14eb..25b2cc396f3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/order_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/order_test.dart @@ -6,28 +6,28 @@ void main() { final instance = Order(); group(Order, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // int petId (default value: null) + // int petId test('to test the property `petId`', () async { // TODO }); - // int quantity (default value: null) + // int quantity test('to test the property `quantity`', () async { // TODO }); - // DateTime shipDate (default value: null) + // DateTime shipDate test('to test the property `shipDate`', () async { // TODO }); // Order Status - // String status (default value: null) + // String status test('to test the property `status`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/outer_composite_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/outer_composite_test.dart index b6231d10498..a48b12809c6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/outer_composite_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/outer_composite_test.dart @@ -6,17 +6,17 @@ void main() { final instance = OuterComposite(); group(OuterComposite, () { - // num myNumber (default value: null) + // num myNumber test('to test the property `myNumber`', () async { // TODO }); - // String myString (default value: null) + // String myString test('to test the property `myString`', () async { // TODO }); - // bool myBoolean (default value: null) + // bool myBoolean test('to test the property `myBoolean`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/pet_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/pet_test.dart index 63cfc070e93..9d5b6e4dd4a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/pet_test.dart @@ -6,33 +6,33 @@ void main() { final instance = Pet(); group(Pet, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // Category category (default value: null) + // Category category test('to test the property `category`', () async { // TODO }); - // String name (default value: null) + // String name test('to test the property `name`', () async { // TODO }); - // BuiltList photoUrls (default value: const []) + // BuiltList photoUrls test('to test the property `photoUrls`', () async { // TODO }); - // BuiltList tags (default value: const []) + // BuiltList tags test('to test the property `tags`', () async { // TODO }); // pet status in the store - // String status (default value: null) + // String status test('to test the property `status`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/read_only_first_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/read_only_first_test.dart index 3c69d593aca..cdb7de301ea 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/read_only_first_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/read_only_first_test.dart @@ -6,12 +6,12 @@ void main() { final instance = ReadOnlyFirst(); group(ReadOnlyFirst, () { - // String bar (default value: null) + // String bar test('to test the property `bar`', () async { // TODO }); - // String baz (default value: null) + // String baz test('to test the property `baz`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/special_model_name_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/special_model_name_test.dart index f23c11a347b..41d8d80eeb0 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/special_model_name_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/special_model_name_test.dart @@ -6,7 +6,7 @@ void main() { final instance = SpecialModelName(); group(SpecialModelName, () { - // int dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket (default value: null) + // int dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket test('to test the property `dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/tag_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/tag_test.dart index c2757a71863..0dbda6e4986 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/tag_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/tag_test.dart @@ -6,12 +6,12 @@ void main() { final instance = Tag(); group(Tag, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // String name (default value: null) + // String name test('to test the property `name`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart index b598e7f7fef..09e720b625c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart @@ -6,43 +6,43 @@ void main() { final instance = User(); group(User, () { - // int id (default value: null) + // int id test('to test the property `id`', () async { // TODO }); - // String username (default value: null) + // String username test('to test the property `username`', () async { // TODO }); - // String firstName (default value: null) + // String firstName test('to test the property `firstName`', () async { // TODO }); - // String lastName (default value: null) + // String lastName test('to test the property `lastName`', () async { // TODO }); - // String email (default value: null) + // String email test('to test the property `email`', () async { // TODO }); - // String password (default value: null) + // String password test('to test the property `password`', () async { // TODO }); - // String phone (default value: null) + // String phone test('to test the property `phone`', () async { // TODO }); // User Status - // int userStatus (default value: null) + // int userStatus test('to test the property `userStatus`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject.md deleted file mode 100644 index 9aa480dee58..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [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/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject1.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject1.md deleted file mode 100644 index 0a92dbfdb95..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/doc/InlineObject1.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject1 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | [**MultipartFile**](MultipartFile.md) | file to upload | [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/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object.dart deleted file mode 100644 index d295239554c..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject { - /// Returns a new [InlineObject] instance. - InlineObject({ - this.name, - this.status, - }); - - /// Updated name of the pet - String name; - - /// Updated status of the pet - String status; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject && - other.name == name && - other.status == status; - - @override - int get hashCode => - (name == null ? 0 : name.hashCode) + - (status == null ? 0 : status.hashCode); - - @override - String toString() => 'InlineObject[name=$name, status=$status]'; - - Map toJson() { - final json = {}; - if (name != null) { - json[r'name'] = name; - } - if (status != null) { - json[r'status'] = status; - } - return json; - } - - /// Returns a new [InlineObject] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject fromJson(Map json) => json == null - ? null - : InlineObject( - name: json[r'name'], - status: json[r'status'], - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object1.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object1.dart deleted file mode 100644 index 95532d1c47f..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/inline_object1.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject1 { - /// Returns a new [InlineObject1] instance. - InlineObject1({ - this.additionalMetadata, - this.file, - }); - - /// Additional data to pass to server - String additionalMetadata; - - /// file to upload - MultipartFile file; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject1 && - other.additionalMetadata == additionalMetadata && - other.file == file; - - @override - int get hashCode => - (additionalMetadata == null ? 0 : additionalMetadata.hashCode) + - (file == null ? 0 : file.hashCode); - - @override - String toString() => 'InlineObject1[additionalMetadata=$additionalMetadata, file=$file]'; - - Map toJson() { - final json = {}; - if (additionalMetadata != null) { - json[r'additionalMetadata'] = additionalMetadata; - } - if (file != null) { - json[r'file'] = file; - } - return json; - } - - /// Returns a new [InlineObject1] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject1 fromJson(Map json) => json == null - ? null - : InlineObject1( - additionalMetadata: json[r'additionalMetadata'], - file: null, // No support for decoding binary content from JSON - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject1.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject1.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject1-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject1.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject.md deleted file mode 100644 index 9aa480dee58..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [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/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject1.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject1.md deleted file mode 100644 index 0a92dbfdb95..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject1.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject1 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | [**MultipartFile**](MultipartFile.md) | file to upload | [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/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject2.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject2.md deleted file mode 100644 index 64edf2983bc..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject2.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject2 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumFormStringArray** | **List** | Form parameter enum test (string array) | [optional] [default to const []] -**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to '-efg'] - -[[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/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject3.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject3.md deleted file mode 100644 index c9a110e7c8c..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject3.md +++ /dev/null @@ -1,28 +0,0 @@ -# openapi.model.InlineObject3 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **int** | None | [optional] -**int32** | **int** | None | [optional] -**int64** | **int** | None | [optional] -**number** | **num** | None | -**float** | **double** | None | [optional] -**double_** | **double** | None | -**string** | **String** | None | [optional] -**patternWithoutDelimiter** | **String** | None | -**byte** | **String** | None | -**binary** | [**MultipartFile**](MultipartFile.md) | None | [optional] -**date** | [**DateTime**](DateTime.md) | None | [optional] -**dateTime** | [**DateTime**](DateTime.md) | None | [optional] -**password** | **String** | None | [optional] -**callback** | **String** | None | [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/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject4.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject4.md deleted file mode 100644 index 3823ffff979..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject4.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject4 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **String** | field1 | -**param2** | **String** | field2 | - -[[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/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject5.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject5.md deleted file mode 100644 index 35879f28bd1..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/InlineObject5.md +++ /dev/null @@ -1,16 +0,0 @@ -# openapi.model.InlineObject5 - -## Load the model package -```dart -import 'package:openapi/api.dart'; -``` - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**requiredFile** | [**MultipartFile**](MultipartFile.md) | file to upload | - -[[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/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object.dart deleted file mode 100644 index d295239554c..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject { - /// Returns a new [InlineObject] instance. - InlineObject({ - this.name, - this.status, - }); - - /// Updated name of the pet - String name; - - /// Updated status of the pet - String status; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject && - other.name == name && - other.status == status; - - @override - int get hashCode => - (name == null ? 0 : name.hashCode) + - (status == null ? 0 : status.hashCode); - - @override - String toString() => 'InlineObject[name=$name, status=$status]'; - - Map toJson() { - final json = {}; - if (name != null) { - json[r'name'] = name; - } - if (status != null) { - json[r'status'] = status; - } - return json; - } - - /// Returns a new [InlineObject] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject fromJson(Map json) => json == null - ? null - : InlineObject( - name: json[r'name'], - status: json[r'status'], - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object1.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object1.dart deleted file mode 100644 index 95532d1c47f..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object1.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject1 { - /// Returns a new [InlineObject1] instance. - InlineObject1({ - this.additionalMetadata, - this.file, - }); - - /// Additional data to pass to server - String additionalMetadata; - - /// file to upload - MultipartFile file; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject1 && - other.additionalMetadata == additionalMetadata && - other.file == file; - - @override - int get hashCode => - (additionalMetadata == null ? 0 : additionalMetadata.hashCode) + - (file == null ? 0 : file.hashCode); - - @override - String toString() => 'InlineObject1[additionalMetadata=$additionalMetadata, file=$file]'; - - Map toJson() { - final json = {}; - if (additionalMetadata != null) { - json[r'additionalMetadata'] = additionalMetadata; - } - if (file != null) { - json[r'file'] = file; - } - return json; - } - - /// Returns a new [InlineObject1] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject1 fromJson(Map json) => json == null - ? null - : InlineObject1( - additionalMetadata: json[r'additionalMetadata'], - file: null, // No support for decoding binary content from JSON - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject1.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject1.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject1-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject1.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object2.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object2.dart deleted file mode 100644 index 9cb02c86eaa..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object2.dart +++ /dev/null @@ -1,231 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject2 { - /// Returns a new [InlineObject2] instance. - InlineObject2({ - this.enumFormStringArray = const [], - this.enumFormString = const InlineObject2EnumFormStringEnum._('-efg'), - }); - - /// Form parameter enum test (string array) - List enumFormStringArray; - - /// Form parameter enum test (string) - InlineObject2EnumFormStringEnum enumFormString; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject2 && - other.enumFormStringArray == enumFormStringArray && - other.enumFormString == enumFormString; - - @override - int get hashCode => - (enumFormStringArray == null ? 0 : enumFormStringArray.hashCode) + - (enumFormString == null ? 0 : enumFormString.hashCode); - - @override - String toString() => 'InlineObject2[enumFormStringArray=$enumFormStringArray, enumFormString=$enumFormString]'; - - Map toJson() { - final json = {}; - if (enumFormStringArray != null) { - json[r'enum_form_string_array'] = enumFormStringArray; - } - if (enumFormString != null) { - json[r'enum_form_string'] = enumFormString; - } - return json; - } - - /// Returns a new [InlineObject2] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject2 fromJson(Map json) => json == null - ? null - : InlineObject2( - enumFormStringArray: InlineObject2EnumFormStringArrayEnum.listFromJson(json[r'enum_form_string_array']), - enumFormString: InlineObject2EnumFormStringEnum.fromJson(json[r'enum_form_string']), - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject2.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject2.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject2-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject2.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - - -class InlineObject2EnumFormStringArrayEnum { - /// Instantiate a new enum with the provided [value]. - const InlineObject2EnumFormStringArrayEnum._(this.value); - - /// The underlying value of this enum member. - final String value; - - @override - bool operator ==(Object other) => identical(this, other) || - other is InlineObject2EnumFormStringArrayEnum && other.value == value; - - @override - int get hashCode => toString().hashCode; - - @override - String toString() => value; - - String toJson() => value; - - static const greaterThan = InlineObject2EnumFormStringArrayEnum._(r'>'); - static const dollar = InlineObject2EnumFormStringArrayEnum._(r'$'); - - /// List of all possible values in this [enum][InlineObject2EnumFormStringArrayEnum]. - static const values = [ - greaterThan, - dollar, - ]; - - static InlineObject2EnumFormStringArrayEnum fromJson(dynamic value) => - InlineObject2EnumFormStringArrayEnumTypeTransformer().decode(value); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json - .map((value) => InlineObject2EnumFormStringArrayEnum.fromJson(value)) - .toList(growable: true == growable); -} - -/// Transformation class that can [encode] an instance of [InlineObject2EnumFormStringArrayEnum] to String, -/// and [decode] dynamic data back to [InlineObject2EnumFormStringArrayEnum]. -class InlineObject2EnumFormStringArrayEnumTypeTransformer { - const InlineObject2EnumFormStringArrayEnumTypeTransformer._(); - - factory InlineObject2EnumFormStringArrayEnumTypeTransformer() => _instance ??= InlineObject2EnumFormStringArrayEnumTypeTransformer._(); - - String encode(InlineObject2EnumFormStringArrayEnum data) => data.value; - - /// Decodes a [dynamic value][data] to a InlineObject2EnumFormStringArrayEnum. - /// - /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, - /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] - /// cannot be decoded successfully, then an [UnimplementedError] is thrown. - /// - /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, - /// and users are still using an old app with the old code. - InlineObject2EnumFormStringArrayEnum decode(dynamic data, {bool allowNull}) { - switch (data) { - case r'>': return InlineObject2EnumFormStringArrayEnum.greaterThan; - case r'$': return InlineObject2EnumFormStringArrayEnum.dollar; - default: - if (allowNull == false) { - throw ArgumentError('Unknown enum value to decode: $data'); - } - } - return null; - } - - /// Singleton [InlineObject2EnumFormStringArrayEnumTypeTransformer] instance. - static InlineObject2EnumFormStringArrayEnumTypeTransformer _instance; -} - -/// Form parameter enum test (string) -class InlineObject2EnumFormStringEnum { - /// Instantiate a new enum with the provided [value]. - const InlineObject2EnumFormStringEnum._(this.value); - - /// The underlying value of this enum member. - final String value; - - @override - bool operator ==(Object other) => identical(this, other) || - other is InlineObject2EnumFormStringEnum && other.value == value; - - @override - int get hashCode => toString().hashCode; - - @override - String toString() => value; - - String toJson() => value; - - static const abc = InlineObject2EnumFormStringEnum._(r'_abc'); - static const efg = InlineObject2EnumFormStringEnum._(r'-efg'); - static const leftParenthesisXyzRightParenthesis = InlineObject2EnumFormStringEnum._(r'(xyz)'); - - /// List of all possible values in this [enum][InlineObject2EnumFormStringEnum]. - static const values = [ - abc, - efg, - leftParenthesisXyzRightParenthesis, - ]; - - static InlineObject2EnumFormStringEnum fromJson(dynamic value) => - InlineObject2EnumFormStringEnumTypeTransformer().decode(value); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json - .map((value) => InlineObject2EnumFormStringEnum.fromJson(value)) - .toList(growable: true == growable); -} - -/// Transformation class that can [encode] an instance of [InlineObject2EnumFormStringEnum] to String, -/// and [decode] dynamic data back to [InlineObject2EnumFormStringEnum]. -class InlineObject2EnumFormStringEnumTypeTransformer { - const InlineObject2EnumFormStringEnumTypeTransformer._(); - - factory InlineObject2EnumFormStringEnumTypeTransformer() => _instance ??= InlineObject2EnumFormStringEnumTypeTransformer._(); - - String encode(InlineObject2EnumFormStringEnum data) => data.value; - - /// Decodes a [dynamic value][data] to a InlineObject2EnumFormStringEnum. - /// - /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, - /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] - /// cannot be decoded successfully, then an [UnimplementedError] is thrown. - /// - /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, - /// and users are still using an old app with the old code. - InlineObject2EnumFormStringEnum decode(dynamic data, {bool allowNull}) { - switch (data) { - case r'_abc': return InlineObject2EnumFormStringEnum.abc; - case r'-efg': return InlineObject2EnumFormStringEnum.efg; - case r'(xyz)': return InlineObject2EnumFormStringEnum.leftParenthesisXyzRightParenthesis; - default: - if (allowNull == false) { - throw ArgumentError('Unknown enum value to decode: $data'); - } - } - return null; - } - - /// Singleton [InlineObject2EnumFormStringEnumTypeTransformer] instance. - static InlineObject2EnumFormStringEnumTypeTransformer _instance; -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object3.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object3.dart deleted file mode 100644 index c74b8b92529..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object3.dart +++ /dev/null @@ -1,217 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject3 { - /// Returns a new [InlineObject3] instance. - InlineObject3({ - this.integer, - this.int32, - this.int64, - @required this.number, - this.float, - @required this.double_, - this.string, - @required this.patternWithoutDelimiter, - @required this.byte, - this.binary, - this.date, - this.dateTime, - this.password, - this.callback, - }); - - /// None - // minimum: 10 - // maximum: 100 - int integer; - - /// None - // minimum: 20 - // maximum: 200 - int int32; - - /// None - int int64; - - /// None - // minimum: 32.1 - // maximum: 543.2 - num number; - - /// None - // maximum: 987.6 - double float; - - /// None - // minimum: 67.8 - // maximum: 123.4 - double double_; - - /// None - String string; - - /// None - String patternWithoutDelimiter; - - /// None - String byte; - - /// None - MultipartFile binary; - - /// None - DateTime date; - - /// None - DateTime dateTime; - - /// None - String password; - - /// None - String callback; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject3 && - other.integer == integer && - other.int32 == int32 && - other.int64 == int64 && - other.number == number && - other.float == float && - other.double_ == double_ && - other.string == string && - other.patternWithoutDelimiter == patternWithoutDelimiter && - other.byte == byte && - other.binary == binary && - other.date == date && - other.dateTime == dateTime && - other.password == password && - other.callback == callback; - - @override - int get hashCode => - (integer == null ? 0 : integer.hashCode) + - (int32 == null ? 0 : int32.hashCode) + - (int64 == null ? 0 : int64.hashCode) + - (number == null ? 0 : number.hashCode) + - (float == null ? 0 : float.hashCode) + - (double_ == null ? 0 : double_.hashCode) + - (string == null ? 0 : string.hashCode) + - (patternWithoutDelimiter == null ? 0 : patternWithoutDelimiter.hashCode) + - (byte == null ? 0 : byte.hashCode) + - (binary == null ? 0 : binary.hashCode) + - (date == null ? 0 : date.hashCode) + - (dateTime == null ? 0 : dateTime.hashCode) + - (password == null ? 0 : password.hashCode) + - (callback == null ? 0 : callback.hashCode); - - @override - String toString() => 'InlineObject3[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]'; - - Map toJson() { - final json = {}; - if (integer != null) { - json[r'integer'] = integer; - } - if (int32 != null) { - json[r'int32'] = int32; - } - if (int64 != null) { - json[r'int64'] = int64; - } - if (number != null) { - json[r'number'] = number; - } - if (float != null) { - json[r'float'] = float; - } - if (double_ != null) { - json[r'double'] = double_; - } - if (string != null) { - json[r'string'] = string; - } - if (patternWithoutDelimiter != null) { - json[r'pattern_without_delimiter'] = patternWithoutDelimiter; - } - if (byte != null) { - json[r'byte'] = byte; - } - if (binary != null) { - json[r'binary'] = binary; - } - if (date != null) { - json[r'date'] = _dateFormatter.format(date.toUtc()); - } - if (dateTime != null) { - json[r'dateTime'] = dateTime.toUtc().toIso8601String(); - } - if (password != null) { - json[r'password'] = password; - } - if (callback != null) { - json[r'callback'] = callback; - } - return json; - } - - /// Returns a new [InlineObject3] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject3 fromJson(Map json) => json == null - ? null - : InlineObject3( - integer: json[r'integer'], - int32: json[r'int32'], - int64: json[r'int64'], - number: json[r'number'] == null ? - null : - json[r'number'].toDouble(), - float: json[r'float'], - double_: json[r'double'], - string: json[r'string'], - patternWithoutDelimiter: json[r'pattern_without_delimiter'], - byte: json[r'byte'], - binary: null, // No support for decoding binary content from JSON - date: json[r'date'] == null - ? null - : DateTime.parse(json[r'date']), - dateTime: json[r'dateTime'] == null - ? null - : DateTime.parse(json[r'dateTime']), - password: json[r'password'], - callback: json[r'callback'], - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject3.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject3.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject3-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject3.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object4.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object4.dart deleted file mode 100644 index 27ac3c05772..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object4.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject4 { - /// Returns a new [InlineObject4] instance. - InlineObject4({ - @required this.param, - @required this.param2, - }); - - /// field1 - String param; - - /// field2 - String param2; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject4 && - other.param == param && - other.param2 == param2; - - @override - int get hashCode => - (param == null ? 0 : param.hashCode) + - (param2 == null ? 0 : param2.hashCode); - - @override - String toString() => 'InlineObject4[param=$param, param2=$param2]'; - - Map toJson() { - final json = {}; - if (param != null) { - json[r'param'] = param; - } - if (param2 != null) { - json[r'param2'] = param2; - } - return json; - } - - /// Returns a new [InlineObject4] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject4 fromJson(Map json) => json == null - ? null - : InlineObject4( - param: json[r'param'], - param2: json[r'param2'], - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject4.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject4.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject4-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject4.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object5.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object5.dart deleted file mode 100644 index 472b4be5413..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_object5.dart +++ /dev/null @@ -1,82 +0,0 @@ -// -// AUTO-GENERATED FILE, DO NOT MODIFY! -// -// @dart=2.0 - -// ignore_for_file: unused_element, unused_import -// ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: lines_longer_than_80_chars - -part of openapi.api; - -class InlineObject5 { - /// Returns a new [InlineObject5] instance. - InlineObject5({ - this.additionalMetadata, - @required this.requiredFile, - }); - - /// Additional data to pass to server - String additionalMetadata; - - /// file to upload - MultipartFile requiredFile; - - @override - bool operator ==(Object other) => identical(this, other) || other is InlineObject5 && - other.additionalMetadata == additionalMetadata && - other.requiredFile == requiredFile; - - @override - int get hashCode => - (additionalMetadata == null ? 0 : additionalMetadata.hashCode) + - (requiredFile == null ? 0 : requiredFile.hashCode); - - @override - String toString() => 'InlineObject5[additionalMetadata=$additionalMetadata, requiredFile=$requiredFile]'; - - Map toJson() { - final json = {}; - if (additionalMetadata != null) { - json[r'additionalMetadata'] = additionalMetadata; - } - if (requiredFile != null) { - json[r'requiredFile'] = requiredFile; - } - return json; - } - - /// Returns a new [InlineObject5] instance and imports its values from - /// [json] if it's non-null, null if [json] is null. - static InlineObject5 fromJson(Map json) => json == null - ? null - : InlineObject5( - additionalMetadata: json[r'additionalMetadata'], - requiredFile: null, // No support for decoding binary content from JSON - ); - - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => - json == null || json.isEmpty - ? true == emptyIsNull ? null : [] - : json.map((v) => InlineObject5.fromJson(v)).toList(growable: true == growable); - - static Map mapFromJson(Map json) { - final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineObject5.fromJson(v)); - } - return map; - } - - // maps a json object with a list of InlineObject5-objects as value to a dart map - static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { - final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineObject5.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); - }); - } - return map; - } -} - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart index 790140d45a7..355b4140bdd 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart @@ -20,7 +20,7 @@ void main() { // // To test special tags and operation ID starting with number // - //Future call123testSpecialTags(Client client) async + //Future call123testSpecialTags(ModelClient modelClient) async test('test call123testSpecialTags', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart index 004677ba786..f4e1969481c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart @@ -74,7 +74,7 @@ void main() { // // To test \"client\" model // - //Future testClientModel(Client client) async + //Future testClientModel(ModelClient modelClient) async test('test testClientModel', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart index 1cdf662877b..1a0f9658947 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart @@ -20,7 +20,7 @@ void main() { // // To test class name in snake case // - //Future testClassname(Client client) async + //Future testClassname(ModelClient modelClient) async test('test testClassname', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart index d9749c91d24..7743739489a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart @@ -6,12 +6,12 @@ void main() { final instance = FileSchemaTestClass(); group('test FileSchemaTestClass', () { - // MultipartFile file + // ModelFile file test('to test the property `file`', () async { // TODO }); - // List files (default value: const []) + // List files (default value: const []) test('to test the property `files`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java index 012b865ec4d..838e1910886 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java @@ -270,7 +270,7 @@ public class ApiClient extends JavaTimeFormatter { * * @param secrets Hash map from authentication name to its secret. */ - public ApiClient configureApiKeys(HashMap secrets) { + public ApiClient configureApiKeys(Map secrets) { for (Map.Entry authEntry : authentications.entrySet()) { Authentication auth = authEntry.getValue(); if (auth instanceof ApiKeyAuth) { diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index d6a95552497..18bbee1df34 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -397,7 +397,7 @@ public class ApiClient extends JavaTimeFormatter { * * @param secrets Hash map from authentication name to its secret. */ - public ApiClient configureApiKeys(HashMap secrets) { + public ApiClient configureApiKeys(Map secrets) { for (Map.Entry authEntry : authentications.entrySet()) { Authentication auth = authEntry.getValue(); if (auth instanceof ApiKeyAuth) { diff --git a/samples/openapi3/client/petstore/typescript/builds/default/index.ts b/samples/openapi3/client/petstore/typescript/builds/default/index.ts index fe00e36cbd8..de89bb05e70 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/index.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/index.ts @@ -1,7 +1,8 @@ export * from "./http/http"; export * from "./auth/auth"; export * from "./models/all"; -export { createConfiguration, Configuration } from "./configuration" +export { createConfiguration } from "./configuration" +export { Configuration } from "./configuration" export * from "./apis/exception"; export * from "./servers"; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/index.ts b/samples/openapi3/client/petstore/typescript/builds/deno/index.ts index b0cc9f0f93d..c81b0e2421d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/index.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/index.ts @@ -1,10 +1,11 @@ export * from "./http/http.ts"; export * from "./auth/auth.ts"; export * from "./models/all.ts"; -export { createConfiguration, Configuration } from "./configuration.ts" +export { createConfiguration } from "./configuration.ts" +export type { Configuration } from "./configuration.ts" export * from "./apis/exception.ts"; export * from "./servers.ts"; -export { PromiseMiddleware as Middleware } from './middleware.ts'; +export type { PromiseMiddleware as Middleware } from './middleware.ts'; export { PromisePetApi as PetApi, PromiseStoreApi as StoreApi, PromiseUserApi as UserApi } from './types/PromiseAPI.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/index.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/index.ts index ddf4ed98b1d..4d48e5222ad 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/index.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/index.ts @@ -1,7 +1,8 @@ export * from "./http/http"; export * from "./auth/auth"; export * from "./models/all"; -export { createConfiguration, Configuration } from "./configuration" +export { createConfiguration } from "./configuration" +export { Configuration } from "./configuration" export * from "./apis/exception"; export * from "./servers"; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/index.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/index.ts index fe00e36cbd8..de89bb05e70 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/index.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/index.ts @@ -1,7 +1,8 @@ export * from "./http/http"; export * from "./auth/auth"; export * from "./models/all"; -export { createConfiguration, Configuration } from "./configuration" +export { createConfiguration } from "./configuration" +export { Configuration } from "./configuration" export * from "./apis/exception"; export * from "./servers"; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/index.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/index.ts index e3944796cfe..49a513cbb84 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/index.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/index.ts @@ -1,7 +1,8 @@ export * from "./http/http"; export * from "./auth/auth"; export * from "./models/all"; -export { createConfiguration, Configuration } from "./configuration" +export { createConfiguration } from "./configuration" +export { Configuration } from "./configuration" export * from "./apis/exception"; export * from "./servers"; diff --git a/samples/openapi3/client/petstore/typescript/tests/deno/test/api/PetApi_test.ts b/samples/openapi3/client/petstore/typescript/tests/deno/test/api/PetApi_test.ts index 9f56de86eab..f29199404e3 100644 --- a/samples/openapi3/client/petstore/typescript/tests/deno/test/api/PetApi_test.ts +++ b/samples/openapi3/client/petstore/typescript/tests/deno/test/api/PetApi_test.ts @@ -2,7 +2,7 @@ import { assertEquals, assert, fail, -} from "https://deno.land/std@0.58.0/testing/asserts.ts"; +} from "https://deno.land/std@0.82.0/testing/asserts.ts"; import * as petstore from "../../../../builds/deno/index.ts"; const configuration = petstore.createConfiguration(); diff --git a/samples/schema/petstore/ktorm/.openapi-generator-ignore b/samples/schema/petstore/ktorm/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/schema/petstore/ktorm/.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/schema/petstore/ktorm/.openapi-generator/FILES b/samples/schema/petstore/ktorm/.openapi-generator/FILES new file mode 100644 index 00000000000..a0e918f1301 --- /dev/null +++ b/samples/schema/petstore/ktorm/.openapi-generator/FILES @@ -0,0 +1,16 @@ +README.md +build.gradle +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/Tag.md +docs/User.md +ktorm_schema.sql +settings.gradle +src/main/kotlin/org/openapitools/database/models/ApiResponse.kt +src/main/kotlin/org/openapitools/database/models/Category.kt +src/main/kotlin/org/openapitools/database/models/Order.kt +src/main/kotlin/org/openapitools/database/models/Pet.kt +src/main/kotlin/org/openapitools/database/models/Tag.kt +src/main/kotlin/org/openapitools/database/models/User.kt diff --git a/samples/schema/petstore/ktorm/.openapi-generator/VERSION b/samples/schema/petstore/ktorm/.openapi-generator/VERSION new file mode 100644 index 00000000000..c30f0ec2be7 --- /dev/null +++ b/samples/schema/petstore/ktorm/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/ktorm/README.md b/samples/schema/petstore/ktorm/README.md new file mode 100644 index 00000000000..252a12e56d7 --- /dev/null +++ b/samples/schema/petstore/ktorm/README.md @@ -0,0 +1,29 @@ +# org.openapitools.database - Kotlin database library for OpenAPI Petstore + +## Requires + + +## Build + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Supports Mapper using API model classes. +* Supports SQLite types. + + +## Documentation for Models + + - [org.openapitools.database.models.ApiResponse](docs/ApiResponse.md) + - [org.openapitools.database.models.Category](docs/Category.md) + - [org.openapitools.database.models.Order](docs/Order.md) + - [org.openapitools.database.models.Pet](docs/Pet.md) + - [org.openapitools.database.models.Tag](docs/Tag.md) + - [org.openapitools.database.models.User](docs/User.md) + diff --git a/samples/schema/petstore/ktorm/build.gradle b/samples/schema/petstore/ktorm/build.gradle new file mode 100644 index 00000000000..00bc1428565 --- /dev/null +++ b/samples/schema/petstore/ktorm/build.gradle @@ -0,0 +1,35 @@ +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.72' + ext.ktorm_version = '3.2.0' + + repositories { + maven { url "https://repo1.maven.org/maven2" } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' + +repositories { + maven { url "https://repo1.maven.org/maven2" } +} + +test { + useJUnitPlatform() +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.ktorm:ktorm-core:$ktorm_version" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.1.0" +} diff --git a/samples/schema/petstore/ktorm/docs/ApiResponse.md b/samples/schema/petstore/ktorm/docs/ApiResponse.md new file mode 100644 index 00000000000..c928cf6529c --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/ApiResponse.md @@ -0,0 +1,15 @@ + +# Table `ApiResponse` +(mapped from: ApiResponse) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**code** | code | int | | **kotlin.Int** | | [optional] +**type** | type | text | | **kotlin.String** | | [optional] +**message** | message | text | | **kotlin.String** | | [optional] + + + + + diff --git a/samples/schema/petstore/ktorm/docs/Category.md b/samples/schema/petstore/ktorm/docs/Category.md new file mode 100644 index 00000000000..99d06e8a468 --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/Category.md @@ -0,0 +1,13 @@ + +# Table `Category` +(mapped from: Category) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**id** | id | long PRIMARY KEY AUTOINCREMENT | | **kotlin.Long** | | [optional] +**name** | name | text | | **kotlin.String** | | [optional] + + + + diff --git a/samples/schema/petstore/ktorm/docs/Order.md b/samples/schema/petstore/ktorm/docs/Order.md new file mode 100644 index 00000000000..8811e4b8814 --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/Order.md @@ -0,0 +1,21 @@ + +# Table `Order` +(mapped from: Order) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**id** | id | long PRIMARY KEY AUTOINCREMENT | | **kotlin.Long** | | [optional] +**petId** | petId | long | | **kotlin.Long** | | [optional] +**quantity** | quantity | int | | **kotlin.Int** | | [optional] +**shipDate** | shipDate | datetime | | [**java.time.LocalDateTime**](java.time.LocalDateTime.md) | | [optional] +**status** | status | text | | [**status**](#StatusEnum) | Order Status | [optional] +**complete** | complete | boolean | | **kotlin.Boolean** | | [optional] + + + + + + + + diff --git a/samples/schema/petstore/ktorm/docs/Pet.md b/samples/schema/petstore/ktorm/docs/Pet.md new file mode 100644 index 00000000000..ce3effd4afa --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/Pet.md @@ -0,0 +1,41 @@ + +# Table `Pet` +(mapped from: Pet) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**name** | name | text NOT NULL | | **kotlin.String** | | +**photoUrls** | `One-To-Many` | `----` | `----` | **kotlin.Array<kotlin.String>** | | +**id** | id | long PRIMARY KEY AUTOINCREMENT | | **kotlin.Long** | | [optional] +**category** | category | long | | [**Category**](Category.md) | | [optional] [foreignkey] +**tags** | `One-To-Many` | `----` | `----` | [**kotlin.Array<Tag>**](Tag.md) | | [optional] +**status** | status | text | | [**status**](#StatusEnum) | pet status in the store | [optional] + + + +# **Table `PetPhotoUrls`** +(mapped from: PetPhotoUrls) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +pet | pet | long | | kotlin.Long | Primary Key | *one* +photoUrls | photoUrls | text | | kotlin.String | Foreign Key | *many* + + + + + +# **Table `PetTag`** +(mapped from: PetTag) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +pet | pet | long | | kotlin.Long | Primary Key | *one* +tag | tag | long | | kotlin.Long | Foreign Key | *many* + + + + diff --git a/samples/schema/petstore/ktorm/docs/Tag.md b/samples/schema/petstore/ktorm/docs/Tag.md new file mode 100644 index 00000000000..ec4d5b8d24d --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/Tag.md @@ -0,0 +1,13 @@ + +# Table `Tag` +(mapped from: Tag) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**id** | id | long PRIMARY KEY AUTOINCREMENT | | **kotlin.Long** | | [optional] +**name** | name | text | | **kotlin.String** | | [optional] + + + + diff --git a/samples/schema/petstore/ktorm/docs/User.md b/samples/schema/petstore/ktorm/docs/User.md new file mode 100644 index 00000000000..e1844a245d0 --- /dev/null +++ b/samples/schema/petstore/ktorm/docs/User.md @@ -0,0 +1,25 @@ + +# Table `User` +(mapped from: User) + +## Properties +Name | Mapping | SQL Type | Default | Type | Description | Notes +---- | ------- | -------- | ------- | ---- | ----------- | ----- +**id** | id | long PRIMARY KEY AUTOINCREMENT | | **kotlin.Long** | | [optional] +**username** | username | text | | **kotlin.String** | | [optional] +**firstName** | firstName | text | | **kotlin.String** | | [optional] +**lastName** | lastName | text | | **kotlin.String** | | [optional] +**email** | email | text | | **kotlin.String** | | [optional] +**password** | password | text | | **kotlin.String** | | [optional] +**phone** | phone | text | | **kotlin.String** | | [optional] +**userStatus** | userStatus | int | | **kotlin.Int** | User Status | [optional] + + + + + + + + + + diff --git a/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.jar b/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..0d4a9516871 Binary files /dev/null and b/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.properties b/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..7dc503f149d --- /dev/null +++ b/samples/schema/petstore/ktorm/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/schema/petstore/ktorm/gradlew b/samples/schema/petstore/ktorm/gradlew new file mode 100644 index 00000000000..cccdd3d517f --- /dev/null +++ b/samples/schema/petstore/ktorm/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/samples/schema/petstore/ktorm/gradlew.bat b/samples/schema/petstore/ktorm/gradlew.bat new file mode 100644 index 00000000000..f9553162f12 --- /dev/null +++ b/samples/schema/petstore/ktorm/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/schema/petstore/ktorm/ktorm_schema.sql b/samples/schema/petstore/ktorm/ktorm_schema.sql new file mode 100644 index 00000000000..e053107143c --- /dev/null +++ b/samples/schema/petstore/ktorm/ktorm_schema.sql @@ -0,0 +1,211 @@ + + +-- -------------------------------------------------------------------------- +-- Table structure for table `ApiResponse` generated from model 'apiResponse' +-- Describes the result of uploading an image resource +-- + +CREATE TABLE IF NOT EXISTS `ApiResponse` ( + `code` int, + `type` text, + `message` text +); /*Describes the result of uploading an image resource*/ + + +-- -------------------------------------------------------------------------- +-- Table structure for table `Category` generated from model 'category' +-- A category for a pet +-- + +CREATE TABLE IF NOT EXISTS `Category` ( + `id` long PRIMARY KEY AUTOINCREMENT, + `name` text +); /*A category for a pet*/ + + +-- -------------------------------------------------------------------------- +-- Table structure for table `Order` generated from model 'order' +-- An order for a pets from the pet store +-- + +CREATE TABLE IF NOT EXISTS `Order` ( + `id` long PRIMARY KEY AUTOINCREMENT, + `petId` long, + `quantity` int, + `shipDate` datetime, + `status` text /*Order Status*/, + `complete` boolean +); /*An order for a pets from the pet store*/ + + +-- -------------------------------------------------------------------------- +-- Table structure for table `Pet` generated from model 'pet' +-- A pet for sale in the pet store +-- + +CREATE TABLE IF NOT EXISTS `Pet` ( + `name` text NOT NULL, + `id` long PRIMARY KEY AUTOINCREMENT, + `category` long, + `status` text /*pet status in the store*/ +); /*A pet for sale in the pet store*/ + +-- -------------------------------------------------------------------------- +-- Table structure for table `PetPhotoUrls` generated from model 'PetPhotoUrls' + +CREATE TABLE IF NOT EXISTS `PetPhotoUrls` ( + `pet` long NOT NULL + `photoUrls` text NOT NULL +); + +-- -------------------------------------------------------------------------- +-- Table structure for table `PetTag` generated from model 'PetTag' + +CREATE TABLE IF NOT EXISTS `PetTag` ( + `pet` long NOT NULL + `tag` long NOT NULL +); + + +-- -------------------------------------------------------------------------- +-- Table structure for table `Tag` generated from model 'tag' +-- A tag for a pet +-- + +CREATE TABLE IF NOT EXISTS `Tag` ( + `id` long PRIMARY KEY AUTOINCREMENT, + `name` text +); /*A tag for a pet*/ + + +-- -------------------------------------------------------------------------- +-- Table structure for table `User` generated from model 'user' +-- A User who is purchasing from the pet store +-- + +CREATE TABLE IF NOT EXISTS `User` ( + `id` long PRIMARY KEY AUTOINCREMENT, + `username` text, + `firstName` text, + `lastName` text, + `email` text, + `password` text, + `phone` text, + `userStatus` int /*User Status*/ +); /*A User who is purchasing from the pet store*/ + + +-- +-- OAuth2 framework tables +-- Thanks to https://github.com/dsquier/oauth2-server-php-mysql repo +-- + +-- +-- Table structure for table `oauth_clients` +-- +CREATE TABLE IF NOT EXISTS `oauth_clients` ( + `client_id` VARCHAR(80) NOT NULL, + `client_secret` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) DEFAULT NULL, + `grant_types` VARCHAR(80) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + PRIMARY KEY (`client_id`) +); + +-- +-- Table structure for table `oauth_access_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_access_tokens` ( + `access_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`access_token`) +); + +-- +-- Table structure for table `oauth_authorization_codes` +-- +CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` ( + `authorization_code` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) NOT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `id_token` VARCHAR(1000) DEFAULT NULL, + PRIMARY KEY (`authorization_code`) +); + +-- +-- Table structure for table `oauth_refresh_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` ( + `refresh_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`refresh_token`) +); + +-- +-- Table structure for table `oauth_users` +-- +CREATE TABLE IF NOT EXISTS `oauth_users` ( + `username` VARCHAR(80) DEFAULT NULL, + `password` VARCHAR(255) DEFAULT NULL, + `first_name` VARCHAR(80) DEFAULT NULL, + `last_name` VARCHAR(80) DEFAULT NULL, + `email` VARCHAR(2000) DEFAULT NULL, + `email_verified` TINYINT(1) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL +); + +-- +-- Table structure for table `oauth_scopes` +-- +CREATE TABLE IF NOT EXISTS `oauth_scopes` ( + `scope` VARCHAR(80) NOT NULL, + `is_default` TINYINT(1) DEFAULT NULL, + PRIMARY KEY (`scope`) +); + +-- +-- Table structure for table `oauth_jwt` +-- +CREATE TABLE IF NOT EXISTS `oauth_jwt` ( + `client_id` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) NOT NULL +); + +-- +-- Table structure for table `oauth_jti` +-- +CREATE TABLE IF NOT EXISTS `oauth_jti` ( + `issuer` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `audiance` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `jti` VARCHAR(2000) NOT NULL +); + +-- +-- Table structure for table `oauth_public_keys` +-- +CREATE TABLE IF NOT EXISTS `oauth_public_keys` ( + `client_id` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) DEFAULT NULL, + `private_key` VARCHAR(2000) DEFAULT NULL, + `encryption_algorithm` VARCHAR(100) DEFAULT 'RS256' +); + +-- +-- Table structure for table `_db_version` +-- +CREATE TABLE IF NOT EXISTS `_db_version` ( + `version` LONG DEFAULT 1 +); diff --git a/samples/schema/petstore/ktorm/settings.gradle b/samples/schema/petstore/ktorm/settings.gradle new file mode 100644 index 00000000000..10cb73142be --- /dev/null +++ b/samples/schema/petstore/ktorm/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'ktorm' \ No newline at end of file diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..7fd492fb229 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,38 @@ +/** +* 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 +* +* +* When I made the templates I intended to import the actual model from kotlin-client +* to support https://www.ktorm.org/en/define-entities-as-any-kind-of-classes.html +* TODO: implement normal entity https://www.ktorm.org/en/entities-and-column-binding.html +* +*/ +package org.openapitools.client.models + + +import java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..f6434894864 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Category.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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..aed804109d5 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,60 @@ +/** +* 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 java.io.Serializable + +/** + * 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, //manual fix: we don't support offsets + /* Order Status */ + //@Json(name = "status") + val status: Order.Status? = null, + //@Json(name = "complete") + val complete: kotlin.Boolean? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..e836d714867 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,62 @@ +/** +* 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 java.io.Serializable + +/** + * 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.collections.List, + //@Json(name = "id") + val id: kotlin.Long? = null, + //@Json(name = "category") + val category: Category? = null, + //@Json(name = "tags") + val tags: kotlin.collections.List? = null, + /* pet status in the store */ + //@Json(name = "status") + val status: Pet.Status? = null +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * 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/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..ba5645a804d --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/Tag.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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..18ba46e5ecc --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,53 @@ +/** +* 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 java.io.Serializable + +/** + * 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 +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/ApiResponse.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/ApiResponse.kt new file mode 100644 index 00000000000..055682fab68 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/ApiResponse.kt @@ -0,0 +1,63 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +object ApiResponses : BaseTable("ApiResponse") { + val code = int("code") /* null */ + val type = text("type") /* null */ + val message = text("message") /* null */ + + /** + * Create an entity of type ApiResponse from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = ApiResponse( + code = row[code] /* kotlin.Int? */, + type = row[type] /* kotlin.String? */, + message = row[message] /* kotlin.String? */ + ) + + /** + * Assign all the columns from the entity of type ApiResponse to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = ApiResponse() + * database.update(ApiResponses, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: ApiResponse) { + this.apply { + set(ApiResponses.code, entity.code) + set(ApiResponses.type, entity.type) + set(ApiResponses.message, entity.message) + } + } + +} + + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Category.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Category.kt new file mode 100644 index 00000000000..efe6d748f38 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Category.kt @@ -0,0 +1,59 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * A category for a pet + * @param id + * @param name + */ +object Categorys : BaseTable("Category") { + val id = long("id") /* null */ + val name = text("name") /* null */ + + /** + * Create an entity of type Category from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = Category( + id = row[id] /* kotlin.Long? */, + name = row[name] /* kotlin.String? */ + ) + + /** + * Assign all the columns from the entity of type Category to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = Category() + * database.update(Categorys, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: Category) { + this.apply { + set(Categorys.id, entity.id) + set(Categorys.name, entity.name) + } + } + +} + + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Order.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Order.kt new file mode 100644 index 00000000000..296046b8cfe --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Order.kt @@ -0,0 +1,76 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +object Orders : BaseTable("Order") { + val id = long("id") /* null */ + val petId = long("petId") /* null */ + val quantity = int("quantity") /* null */ + val shipDate = datetime("shipDate") /* null */ + val status = text("status").transform({ Order.Status.valueOf(it ?: "placed") }, { it.value }) /* null */ /* Order Status */ + + val complete = boolean("complete") /* null */ + + /** + * Create an entity of type Order from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = Order( + id = row[id] /* kotlin.Long? */, + petId = row[petId] /* kotlin.Long? */, + quantity = row[quantity] /* kotlin.Int? */, + shipDate = row[shipDate] /* java.time.LocalDateTime? */, + status = row[status] /* kotlin.String? */ /* Order Status */, + complete = row[complete] /* kotlin.Boolean? */ + ) + + /** + * Assign all the columns from the entity of type Order to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = Order() + * database.update(Orders, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: Order) { + this.apply { + set(Orders.id, entity.id) + set(Orders.petId, entity.petId) + set(Orders.quantity, entity.quantity) + set(Orders.shipDate, entity.shipDate) + set(Orders.status, entity.status) + set(Orders.complete, entity.complete) + } + } + +} + + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Pet.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Pet.kt new file mode 100644 index 00000000000..f6ceae6bc63 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Pet.kt @@ -0,0 +1,104 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * 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 + */ +object Pets : BaseTable("Pet") { + val name = text("name") + val id = long("id") /* null */ + val category = long("category") /* null */ + val status = text("status").transform({ Pet.Status.valueOf(it ?: "available") }, { it.value }) /* null */ /* pet status in the store */ + + + /** + * Create an entity of type Pet from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = Pet( + name = row[name] ?: "" /* kotlin.String */, + photoUrls = emptyList() /* kotlin.Array */, + id = row[id] /* kotlin.Long? */, + category = Categorys.createEntity(row, withReferences) /* Category? */, + tags = emptyList() /* kotlin.Array? */, + status = row[status] /* kotlin.String? */ /* pet status in the store */ + ) + + /** + * Assign all the columns from the entity of type Pet to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = Pet() + * database.update(Pets, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: Pet) { + this.apply { + set(Pets.name, entity.name) + set(Pets.id, entity.id) + set(Pets.category, entity.category) + set(Pets.status, entity.status) + } + } + +} + + +object PetPhotoUrls : BaseTable>("PetPhotoUrls") { + val pet = long("pet") + val photoUrls = text("photoUrls") + + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean): Pair = + Pair(row[pet] ?: 0, row[photoUrls] ?: "") + + fun AssignmentsBuilder.assignFrom(entity: Pair) { + this.apply { + set(PetPhotoUrls.pet, entity.first) + set(PetPhotoUrls.photoUrls, entity.second) + } + } + +} + +object PetTag : BaseTable>("PetTag") { + val pet = long("pet") + val tag = long("tag") + + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean): Pair = + Pair(row[pet] ?: 0, row[tag] ?: 0) + + fun AssignmentsBuilder.assignFrom(entity: Pair) { + this.apply { + set(PetTag.pet, entity.first) + set(PetTag.tag, entity.second) + } + } + +} + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Tag.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Tag.kt new file mode 100644 index 00000000000..1f614872898 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/Tag.kt @@ -0,0 +1,59 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * A tag for a pet + * @param id + * @param name + */ +object Tags : BaseTable("Tag") { + val id = long("id") /* null */ + val name = text("name") /* null */ + + /** + * Create an entity of type Tag from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = Tag( + id = row[id] /* kotlin.Long? */, + name = row[name] /* kotlin.String? */ + ) + + /** + * Assign all the columns from the entity of type Tag to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = Tag() + * database.update(Tags, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: Tag) { + this.apply { + set(Tags.id, entity.id) + set(Tags.name, entity.name) + } + } + +} + + diff --git a/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/User.kt b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/User.kt new file mode 100644 index 00000000000..98c31bf1be5 --- /dev/null +++ b/samples/schema/petstore/ktorm/src/main/kotlin/org/openapitools/database/models/User.kt @@ -0,0 +1,83 @@ +/** +* 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.database.models + +import org.ktorm.dsl.* +import org.ktorm.schema.* +import org.ktorm.database.Database +import org.openapitools.client.models.* + + +/** + * 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 + */ +object Users : BaseTable("User") { + val id = long("id") /* null */ + val username = text("username") /* null */ + val firstName = text("firstName") /* null */ + val lastName = text("lastName") /* null */ + val email = text("email") /* null */ + val password = text("password") /* null */ + val phone = text("phone") /* null */ + val userStatus = int("userStatus") /* null */ /* User Status */ + + /** + * Create an entity of type User from the model + */ + override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = User( + id = row[id] /* kotlin.Long? */, + username = row[username] /* kotlin.String? */, + firstName = row[firstName] /* kotlin.String? */, + lastName = row[lastName] /* kotlin.String? */, + email = row[email] /* kotlin.String? */, + password = row[password] /* kotlin.String? */, + phone = row[phone] /* kotlin.String? */, + userStatus = row[userStatus] /* kotlin.Int? */ /* User Status */ + ) + + /** + * Assign all the columns from the entity of type User to the DML expression. + * + * Usage: + * + * ```kotlin + * let entity = User() + * database.update(Users, { + * assignFrom(entity) + * }) + * ``` + * @return the builder with the columns for the update or insert. + */ + fun AssignmentsBuilder.assignFrom(entity: User) { + this.apply { + set(Users.id, entity.id) + set(Users.username, entity.username) + set(Users.firstName, entity.firstName) + set(Users.lastName, entity.lastName) + set(Users.email, entity.email) + set(Users.password, entity.password) + set(Users.phone, entity.phone) + set(Users.userStatus, entity.userStatus) + } + } + +} + + diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/model/Pet.kt index 3b7d8a1918e..22bbe695c0d 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/model/Pet.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/model/Pet.kt @@ -26,13 +26,11 @@ import io.swagger.annotations.ApiModelProperty */ data class Pet( - @get:NotNull @ApiModelProperty(example = "doggie", required = true, value = "") - @field:JsonProperty("name") val name: kotlin.String, + @field:JsonProperty("name", required = true) val name: kotlin.String, - @get:NotNull @ApiModelProperty(example = "null", required = true, value = "") - @field:JsonProperty("photoUrls") val photoUrls: kotlin.collections.List, + @field:JsonProperty("photoUrls", required = true) val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", value = "") @field:JsonProperty("id") val id: kotlin.Long? = null, 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 3b7d8a1918e..22bbe695c0d 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 @@ -26,13 +26,11 @@ import io.swagger.annotations.ApiModelProperty */ data class Pet( - @get:NotNull @ApiModelProperty(example = "doggie", required = true, value = "") - @field:JsonProperty("name") val name: kotlin.String, + @field:JsonProperty("name", required = true) val name: kotlin.String, - @get:NotNull @ApiModelProperty(example = "null", required = true, value = "") - @field:JsonProperty("photoUrls") val photoUrls: kotlin.collections.List, + @field:JsonProperty("photoUrls", required = true) val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", value = "") @field:JsonProperty("id") val id: kotlin.Long? = null, 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 3b7d8a1918e..22bbe695c0d 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 @@ -26,13 +26,11 @@ import io.swagger.annotations.ApiModelProperty */ data class Pet( - @get:NotNull @ApiModelProperty(example = "doggie", required = true, value = "") - @field:JsonProperty("name") val name: kotlin.String, + @field:JsonProperty("name", required = true) val name: kotlin.String, - @get:NotNull @ApiModelProperty(example = "null", required = true, value = "") - @field:JsonProperty("photoUrls") val photoUrls: kotlin.collections.List, + @field:JsonProperty("photoUrls", required = true) val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", value = "") @field:JsonProperty("id") val id: kotlin.Long? = null,