Compare commits

..

2 Commits

Author SHA1 Message Date
William Cheng
a049e4c271 better comment 2019-08-19 18:06:27 +08:00
William Cheng
eee7a40629 remove dollar sign from java const name 2019-08-19 15:42:59 +08:00
333 changed files with 2203 additions and 5765 deletions

View File

@@ -2,13 +2,6 @@ kind: pipeline
name: default
steps:
# test Dart 2.x petstore client
- name: dart2x-test
image: google/dart
commands:
- (cd samples/client/petstore/dart-jaguar/openapi && pub get && pub run build_runner build --delete-conflicting-outputs)
- (cd samples/client/petstore/dart-jaguar/flutter_petstore/openapi && pub get && pub run build_runner build --delete-conflicting-outputs)
- (cd samples/client/petstore/dart2/openapi && pub get && pub run test)
# test Java 11 HTTP client
- name: java11-test
image: hirokimatsumoto/alpine-openjdk-11

View File

@@ -1,73 +0,0 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptFetchBuildNamespaceParameterInterfacesPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Petstore Client (with namespacing for parameter interfaces)</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-build</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -66,7 +66,7 @@ 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), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **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), **Kotlin**, **Lua**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.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)), **Kotlin** (Spring Boot, Ktor), **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** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**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, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot, Ktor), **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** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
**Others** | **GraphQL**, **JMeter**, **MySQL Schema**
@@ -569,7 +569,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Klarna](https://www.klarna.com/)
- [Metaswitch](https://www.metaswitch.com/)
- [Myworkout](https://myworkout.com)
- [Paxos](https://www.paxos.com)
- [Prometheus/Alertmanager](https://github.com/prometheus/alertmanager)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
- [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development)
@@ -756,7 +755,6 @@ Here is a list of template creators:
* Configuration
* Apache2: @stkrwork
* Schema
* Avro: @sgadouar
* GraphQL: @wing328 [:heart:](https://www.patreon.com/wing328)
* MySQL: @ybelenko

View File

@@ -1,32 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/avro-schema -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g avro-schema -o samples/openapi3/schema/petstore/avro-schema $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -4,4 +4,3 @@
./bin/openapi3/typescript-fetch-petstore-with-npm-version.sh
./bin/openapi3/typescript-fetch-petstore-interfaces.sh
./bin/openapi3/typescript-fetch-petstore.sh
./bin/openapi3/typescript-fetch-petstore-namespace-parameter-interfaces.sh

View File

@@ -1,32 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g typescript-fetch -o samples/client/petstore/typescript-fetch/builds/namespace-parameter-interfaces --additional-properties namespaceParameterInterfaces=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -4,5 +4,4 @@
./bin/typescript-fetch-petstore-with-npm-version.sh
./bin/typescript-fetch-petstore-interfaces.sh
./bin/typescript-fetch-petstore.sh
./bin/typescript-fetch-petstore-multiple-parameters.sh
./bin/typescript-fetch-petstore-namespace-parameter-interfaces.sh
./bin/typescript-fetch-petstore-multiple-parameters.sh

View File

@@ -1,7 +0,0 @@
{
"npmName": "@openapitools/typescript-fetch-petstore",
"npmVersion": "1.0.0",
"npmRepository" : "https://skimdb.npmjs.com/registry",
"snapshot" : false,
"namespaceParameterInterfaces": true
}

View File

@@ -1,34 +0,0 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-fetch -c bin/typescript-fetch-petstore-namespace-parameter-interfaces.json -o samples/client/petstore/typescript-fetch/builds/namespace-parameter-interfaces $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/namespace-parameter-interfaces/pom.xml samples/client/petstore/typescript-fetch/builds/namespace-parameter-interfaces/pom.xml

View File

@@ -59,9 +59,6 @@ declare -a scripts=(
"./bin/apex-petstore.sh"
"./bin/perl-petstore-all.sh"
"./bin/dart-jaguar-petstore.sh"
"./bin/dart-flutter-petstore.sh"
"./bin/dart-petstore.sh"
"./bin/dart2-petstore.sh"
#"./bin/elm-petstore-all.sh"
"./bin/meta-codegen.sh"
# OTHERS

View File

@@ -5,4 +5,3 @@ call bin\windows\typescript-fetch-petstore-target-es6.bat
call bin\windows\typescript-fetch-petstore-with-npm-version.bat
call bin\windows\typescript-fetch-petstore-interfaces.bat
call bin\windows\typescript-fetch-petstore-multiple-parameters.bat
call bin\windows\typescript-fetch-petstore-namespace-parameter-interfaces.bat

View File

@@ -1,12 +0,0 @@
@ECHO OFF
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g typescript-fetch -o samples\client\petstore\typescript-fetch\builds\namespace-parameter-interfaces --additional-properties namespaceParameterInterfaces=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -125,7 +125,6 @@ The following generators are available:
## SCHEMA generators
* [avro-schema (beta)](generators/avro-schema)
* [mysql-schema](generators/mysql-schema)

View File

@@ -1,14 +0,0 @@
---
id: generator-opts-schema-avro-schema
title: Config Options for avro-schema
sidebar_label: avro-schema
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|packageName|package for generated classes (where supported)| |null|

View File

@@ -12,7 +12,7 @@ sidebar_label: csharp-netcore
|sourceFolder|source folder for generated code| |src|
|packageGuid|The GUID that will be associated with the C# project| |null|
|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dl>|netstandard2.0|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dl>|v4.6.1|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
@@ -26,4 +26,3 @@ sidebar_label: csharp-netcore
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false|
|validatable|Generates self-validatable models.| |true|
|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false|

View File

@@ -13,5 +13,4 @@ sidebar_label: go-experimental
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|enumClassPrefix|Prefix enum with class name| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|

View File

@@ -13,5 +13,4 @@ sidebar_label: go
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|enumClassPrefix|Prefix enum with class name| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|

View File

@@ -19,4 +19,3 @@ sidebar_label: typescript-fetch
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |true|
|namespaceParameterInterfaces|Setting this property to true will generate parameter interface declarations within a dedicated namespace to avoid name conflicts.| |false|

View File

@@ -3,7 +3,7 @@ id: swagger-codegen-migration
title: Migrating from Swagger Codegen
---
OpenAPI Generator is a fork of `swagger-codegen` between version `2.3.1` and `2.4.0`. For the reasons behind the fork, please refer to the [Q&A](https://github.com/OpenAPITools/openapi-generator/blob/master/docs/qna.md).
OpenAPI Generator is a fork of `swagger-codegen` between version `2.3.1` and `2.4.0`.
This community-driven version called "OpenAPI Generator" provides similar functionalities and can be used as drop-in replacement.
This guide explains the major differences in order to help you with the migration.
@@ -22,7 +22,6 @@ This guide explains the major differences in order to help you with the migratio
- [New fully qualified name for the classes](#new-fully-qualified-name-for-the-classes)
- [Body parameter name](#body-parameter-name)
- [Default basePath](#default-basepath)
- [Nullable](#nullable)
## New docker images
@@ -251,7 +250,3 @@ If your API client is using named parameters in the function call (e.g. Perl req
## Default basePath
The default `basePath` has been changed from `https://localhost` to `http://localhost` (http without s)
## Nullable
OpenAPI spec v3 has better support for `nullable`. If you're still using OpenAPI/Swagger spec v2, please use `x-nullable: true` instead.

View File

@@ -268,12 +268,6 @@
<!-- <version>${testng-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.14.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>

View File

@@ -308,7 +308,4 @@ public class CodegenConstants {
public static final String EXCEPTION_ON_FAILURE = "returnExceptionOnFailure";
public static final String EXCEPTION_ON_FAILURE_DESC = "Throw an exception on non success response codes";
public static final String ENUM_CLASS_PREFIX = "enumClassPrefix";
public static final String ENUM_CLASS_PREFIX_DESC = "Prefix enum with class name";
}

View File

@@ -38,7 +38,6 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
protected boolean withGoCodegenComment = false;
protected boolean withXml = false;
protected boolean enumClassPrefix = false;
protected String packageName = "openapi";
@@ -619,10 +618,6 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
this.withXml = withXml;
}
public void setEnumClassPrefix(boolean enumClassPrefix) {
this.enumClassPrefix = enumClassPrefix;
}
@Override
public String toDefaultValue(Schema schema) {
if (schema.getDefault() != null) {

View File

@@ -17,6 +17,7 @@
package org.openapitools.codegen.languages;
import com.google.common.base.CaseFormat;
import com.google.common.base.Strings;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
@@ -984,6 +985,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
model.imports.add("ApiModelProperty");
model.imports.add("ApiModel");
}
// store java constant property name in vendor extension, remove dollar sign from the constant name
property.vendorExtensions.put("x-java-const-name", CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, property.nameInCamelCase.replaceAll("\\$", "")));
}
@Override

View File

@@ -1,135 +0,0 @@
/*
* Copyright 2019 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class AvroSchemaCodegen extends DefaultCodegen implements CodegenConfig {
private static final String AVRO = "avro-schema";
protected String packageName = "model";
public AvroSchemaCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
outputFolder = "generated-code/avro-schema";
modelTemplateFiles.put("model.mustache", ".avsc");
apiPackage = "api";
modelPackage = "model";
importMapping.clear();
embeddedTemplateDir = templateDir = AVRO;
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
languageSpecificPrimitives = new HashSet<>(
Arrays.asList("null", "boolean", "int", "integer", "long", "float", "double", "bytes", "string",
"BigDecimal", "UUID", "number", "date", "DateTime")
);
defaultIncludes = new HashSet<>(languageSpecificPrimitives);
instantiationTypes.put("array", "Array");
instantiationTypes.put("list", "Array");
instantiationTypes.put("map", "Object");
typeMapping.clear();
typeMapping.put("number", "double");
typeMapping.put("DateTime", "string");
typeMapping.put("date", "string");
typeMapping.put("short", "int");
typeMapping.put("char", "string");
typeMapping.put("integer", "int");
typeMapping.put("ByteArray", "bytes");
typeMapping.put("binary", "File");
typeMapping.put("file", "File");
typeMapping.put("UUID", "string");
typeMapping.put("BigDecimal", "string");
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, CodegenConstants.PACKAGE_NAME_DESC));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME);
}
additionalProperties.put("packageName", packageName);
}
@Override
public CodegenType getTag() {
return CodegenType.SCHEMA;
}
@Override
public String getName() {
return "avro-schema";
}
@Override
public String getHelp() {
return "Generates a Avro model (beta).";
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return postProcessModelsEnum(objs);
}
@Override
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
super.setNonArrayMapProperty(property, type);
if (property.isModel) {
property.dataType = camelize(modelNamePrefix + property.dataType + modelNameSuffix);
}
}
@Override
public String escapeUnsafeCharacters(String input) {
// do nothing as it's a schema conversion
return input;
}
@Override
public String escapeQuotationMark(String input) {
// do nothing as it's a schema conversion
return input;
}
}

View File

@@ -65,7 +65,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected String modelDocPath = "docs/";
// Defines TargetFrameworkVersion in csproj files
protected String targetFramework = defaultFramework.name;
protected String targetFramework = defaultFramework.dotNetFrameworkVersion;
// Defines nuget identifiers for target framework
protected String targetFrameworkNuget = targetFramework;
@@ -78,8 +78,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
// By default, generated code is considered public
protected boolean nonPublicApi = Boolean.FALSE;
protected boolean caseInsensitiveResponseHeaders = Boolean.FALSE;
public CSharpNetCoreClientCodegen() {
super();
@@ -208,10 +206,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.VALIDATABLE_DESC,
this.validatable);
addSwitch(CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS,
CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS_DESC,
this.caseInsensitiveResponseHeaders);
regexModifiers = new HashMap<>();
regexModifiers.put('i', "IgnoreCase");
regexModifiers.put('m', "Multiline");
@@ -476,7 +470,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
clientPackage = "Client";
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name);
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.dotNetFrameworkVersion);
FrameworkStrategy strategy = defaultFramework;
for (FrameworkStrategy frameworkStrategy : frameworkStrategies) {
if (framework.equals(frameworkStrategy.name)) {
@@ -487,7 +481,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
strategy.configureAdditionalProperties(additionalProperties);
setTargetFrameworkNuget(strategy.getNugetFrameworkIdentifier());
setTargetFramework(strategy.name);
setTargetFramework(strategy.dotNetFrameworkVersion);
if (strategy != FrameworkStrategy.NETSTANDARD_2_0) {
LOGGER.warn("If using built-in templates-RestSharp only supports netstandard 2.0 or later.");
@@ -646,10 +640,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.validatable = validatable;
}
public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) {
this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders;
}
@Override
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
@@ -810,7 +800,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
protected void configureAdditionalProperties(final Map<String, Object> properties) {
properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.name);
properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.dotNetFrameworkVersion);
// not intended to be user-settable
properties.put(TARGET_FRAMEWORK_IDENTIFIER, this.getTargetFrameworkIdentifier());

View File

@@ -55,7 +55,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
@@ -114,13 +114,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
}
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
if (enumClassPrefix) {
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, "true");
}
}
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
if (isGoSubmodule) {

View File

@@ -33,11 +33,9 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
public static final String NAMESPACE_PARAMETER_INTERFACES = "namespaceParameterInterfaces";
protected String npmRepository = null;
private boolean useSingleRequestParameter = true;
private boolean namespaceParameterInterfaces = false;
protected boolean addedApiIndex = false;
protected boolean addedModelIndex = false;
@@ -61,7 +59,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString()));
this.cliOptions.add(new CliOption(NAMESPACE_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations within a dedicated namespace to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
@@ -97,11 +94,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
}
writePropertyBack(USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(NAMESPACE_PARAMETER_INTERFACES)) {
this.setNamespaceParameterInterfaces(convertPropertyToBoolean(NAMESPACE_PARAMETER_INTERFACES));
}
writePropertyBack(NAMESPACE_PARAMETER_INTERFACES, getNamespaceParameterInterfaces());
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
@@ -216,7 +208,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
this.addOperationModelImportInfomation(operations);
this.updateOperationParameterEnumInformation(operations);
this.addOperationObjectResponseInformation(operations);
this.addOperationNamespaceParameterInterfacesInformation(operations);
return operations;
}
@@ -263,22 +254,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
}
}
private void addOperationNamespaceParameterInterfacesInformation(Map<String, Object> operations) {
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) _operations.get("operation");
if (!operationList.isEmpty() && getNamespaceParameterInterfaces()) {
operations.put("namespaceParameterInterfaces", true);
operations.put("paramIfaceIndent", " ");
operations.put("paramIfaceSuffix", "");
operations.put("paramIfaceNsPrefix", operationList.get(0).baseName + "Requests.");
} else {
operations.put("namespaceParameterInterfaces", false);
operations.put("paramIfaceIndent", "");
operations.put("paramIfaceSuffix", "Request");
operations.put("paramIfaceNsPrefix", "");
}
}
private void addExtraReservedWords() {
this.reservedWords.add("BASE_PATH");
this.reservedWords.add("BaseAPI");
@@ -314,12 +289,4 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
private void setUseSingleRequestParameter(boolean useSingleRequestParameter) {
this.useSingleRequestParameter = useSingleRequestParameter;
}
private boolean getNamespaceParameterInterfaces() {
return namespaceParameterInterfaces;
}
private void setNamespaceParameterInterfaces(boolean namespaceParameterInterfaces) {
this.namespaceParameterInterfaces = namespaceParameterInterfaces;
}
}

View File

@@ -4,7 +4,7 @@
* If the field is required, always include it, even if it is null.
* Else use custom behaviour, IOW use whatever is defined on the object mapper
}}
@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}})
@JsonProperty(JSON_PROPERTY_{{vendorExtensions.x-java-const-name}})
@JsonInclude({{#isMapContainer}}{{#items.isNullable}}content = JsonInclude.Include.ALWAYS, {{/items.isNullable}}{{/isMapContainer}}value = JsonInclude.Include.{{#required}}ALWAYS{{/required}}{{^required}}USE_DEFAULTS{{/required}})
{{#withXml}}
{{^isContainer}}
@@ -16,4 +16,4 @@
@JacksonXmlElementWrapper(useWrapping = {{isXmlWrapped}}, {{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}localName = "{{#items.xmlName}}{{items.xmlName}}{{/items.xmlName}}{{^items.xmlName}}{{items.baseName}}{{/items.xmlName}}")
{{/isXmlWrapped}}
{{/isContainer}}
{{/withXml}}
{{/withXml}}

View File

@@ -6,7 +6,6 @@ import {{invokerPackage}}.ApiClient;
{{/imports}}
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.InputStreamContent;
@@ -108,7 +107,7 @@ public class {{classname}} {
String localVarUrl = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}}
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = {{#isBodyAllowed}}{{#bodyParam}}apiClient.new JacksonJsonHttpContent({{paramName}}){{/bodyParam}}{{^bodyParam}}new EmptyContent(){{/bodyParam}}{{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
HttpContent content = {{#isBodyAllowed}}apiClient.new JacksonJsonHttpContent({{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}){{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}{{#bodyParam}}
@@ -180,7 +179,7 @@ public class {{classname}} {
String localVarUrl = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}}
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = {{#isBodyAllowed}}{{#bodyParam}}apiClient.new JacksonJsonHttpContent({{paramName}}){{/bodyParam}}{{^bodyParam}}new EmptyContent(){{/bodyParam}}{{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
HttpContent content = {{#isBodyAllowed}}apiClient.new JacksonJsonHttpContent({{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}){{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}

View File

@@ -704,7 +704,7 @@ public class ApiClient {
}
}
Entity<?> entity = (body == null) ? Entity.json("") : serialize(body, formParams, contentType);
Entity<?> entity = serialize(body, formParams, contentType);
Response response = null;
@@ -716,13 +716,11 @@ public class ApiClient {
} else if ("PUT".equals(method)) {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.method("DELETE", entity);
response = invocationBuilder.delete();
} else if ("PATCH".equals(method)) {
response = invocationBuilder.method("PATCH", entity);
} else if ("HEAD".equals(method)) {
response = invocationBuilder.head();
} else if ("OPTIONS".equals(method)) {
response = invocationBuilder.options();
} else if ("TRACE".equals(method)) {
response = invocationBuilder.trace();
} else {
@@ -776,8 +774,6 @@ public class ApiClient {
clientConfig.register(json);
clientConfig.register(JacksonFeature.class);
clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
// turn off compliance validation to be able to send payloads with DELETE calls
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
if (debugging) {
{{^supportJava6}}
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
@@ -788,9 +784,6 @@ public class ApiClient {
{{#supportJava6}}
clientConfig.register(new LoggingFilter(java.util.logging.Logger.getLogger(LoggingFilter.class.getName()), true));
{{/supportJava6}}
} else {
// suppress warnings for payloads with DELETE calls:
java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);
}
performAdditionalClientConfiguration(clientConfig);
return ClientBuilder.newClient(clientConfig);

View File

@@ -107,7 +107,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {

View File

@@ -90,7 +90,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
// create path and map variables
String localVarPath = "{{{path}}}"{{#pathParams}}

View File

@@ -41,7 +41,6 @@ import org.jboss.resteasy.spi.ResteasyProviderFactory;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.OAuth;
@@ -79,9 +78,8 @@ public class ApiClient {
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
@@ -663,13 +661,11 @@ public class ApiClient {
} else if ("PUT".equals(method)) {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.method("DELETE", entity);
response = invocationBuilder.delete();
} else if ("PATCH".equals(method)) {
response = invocationBuilder.method("PATCH", entity);
response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity);
} else if ("HEAD".equals(method)) {
response = invocationBuilder.head();
} else if ("OPTIONS".equals(method)) {
response = invocationBuilder.options();
} else if ("TRACE".equals(method)) {
response = invocationBuilder.trace();
} else {

View File

@@ -57,7 +57,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {

View File

@@ -41,11 +41,11 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
{{/isXmlAttribute}}
{{/withXml}}
{{#gson}}
public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}";
@SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}})
public static final String SERIALIZED_NAME_{{vendorExtensions.x-java-const-name}} = "{{baseName}}";
@SerializedName(SERIALIZED_NAME_{{vendorExtensions.x-java-const-name}})
{{/gson}}
{{#jackson}}
public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}";
public static final String JSON_PROPERTY_{{vendorExtensions.x-java-const-name}} = "{{baseName}}";
{{/jackson}}
{{#vendorExtensions.isJacksonOptionalNullable}}
{{#isContainer}}
@@ -197,7 +197,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
{{^isReadOnly}}
{{#vendorExtensions.isJacksonOptionalNullable}}
@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}})
@JsonProperty(JSON_PROPERTY_{{vendorExtensions.x-java-const-name}})
public void {{setter}}_JsonNullable(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) {
this.{{name}} = {{name}};
}

View File

@@ -4,7 +4,6 @@ org.openapitools.codegen.languages.AndroidClientCodegen
org.openapitools.codegen.languages.Apache2ConfigCodegen
org.openapitools.codegen.languages.ApexClientCodegen
org.openapitools.codegen.languages.AspNetCoreServerCodegen
org.openapitools.codegen.languages.AvroSchemaCodegen
org.openapitools.codegen.languages.BashClientCodegen
org.openapitools.codegen.languages.CLibcurlClientCodegen
org.openapitools.codegen.languages.ClojureClientCodegen

View File

@@ -1,11 +0,0 @@
{{#models}}
{{#model}}
{
"namespace": "{{packageName}}",
"type": "{{#isEnum}}enum{{/isEnum}}{{^isEnum}}record{{/isEnum}}",
"doc": "{{{description}}}",
"name": "{{{classname}}}",
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
}
{{/model}}
{{/models}}

View File

@@ -1,3 +0,0 @@
"symbols": [{{#allowableValues}}{{#enumVars}}
{{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
]

View File

@@ -1,9 +0,0 @@
"fields": [
{{#vars}}
{
"name": "{{baseName}}",
"type": {{^required}}["null", {{/required}}{{>typeProperty}}{{^required}}]{{/required}},
"doc": "{{{description}}}"
}{{^-last}},{{/-last}}
{{/vars}}
]

View File

@@ -1,4 +0,0 @@
{
"type": "{{dataType}}",
{{#items}}"items": "{{#isModel}}{{package}}.{{/isModel}}{{dataType}}"{{/items}}
}

View File

@@ -1,7 +0,0 @@
{
"type": "enum",
"name": "{{classname}}_{{name}}",
"symbols": [{{#allowableValues}}{{#enumVars}}
{{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
]
}

View File

@@ -1 +0,0 @@
{{^isEnum}}{{^isContainer}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType}}{{#isModel}}"{{package}}.{{dataType}}"{{/isModel}}{{/isContainer}}{{#isContainer}}{{>typeArray}}{{/isContainer}}{{/isEnum}}{{#isEnum}}{{>typeEnum}}{{/isEnum}}

View File

@@ -347,7 +347,7 @@ namespace {{packageName}}.Client
private ApiResponse<T> toApiResponse<T>({{#supportsAsync}}IRestResponse<T> response{{/supportsAsync}}{{^supportsAsync}}IRestResponse response, CustomJsonCodec des{{/supportsAsync}})
{
T result = {{#supportsAsync}}response.Data{{/supportsAsync}}{{^supportsAsync}}(T)des.Deserialize(response, typeof(T)){{/supportsAsync}};
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result)
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()

View File

@@ -21,26 +21,6 @@ namespace {{packageName}}.Client
#endregion Private Fields
#region Constructors
/// <summary>
/// Empty Constructor.
/// </summary>
public Multimap()
{
_dictionary = new {{^net35}}Concurrent{{/net35}}Dictionary<T, IList<TValue>>();
}
/// <summary>
/// Constructor with comparer.
/// </summary>
/// <param name="comparer"></param>
public Multimap(IEqualityComparer<T> comparer) {
_dictionary = new {{^net35}}Concurrent{{/net35}}Dictionary<T, IList<TValue>>(comparer);
}
#endregion Constructors
#region Enumerators
/// <summary>

View File

@@ -23,7 +23,9 @@
<RootNamespace>{{packageName}}</RootNamespace>
<AssemblyName>{{packageName}}</AssemblyName>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFramework>{{targetFramework}}</TargetFramework>
<!--<TargetFrameworkVersion>{{targetFramework}}</TargetFrameworkVersion>-->
<TargetFrameworkVersion>{{targetFrameworkVersion}}</TargetFrameworkVersion>
<TargetFrameworkIdentifier>{{targetFrameworkIdentifier}}</TargetFrameworkIdentifier>
<FileAlignment>512</FileAlignment>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\{{packageName}}.xml</DocumentationFile>
</PropertyGroup>
@@ -38,4 +40,6 @@
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
</ItemGroup>
<Import Project="..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
</Project>

View File

@@ -32,11 +32,18 @@
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
</ItemGroup>
<Import Project="..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
<ItemGroup>
<ProjectReference Include="..\{{packageName}}\{{packageName}}.csproj">
<Project>{{packageGuid}}</Project>
<Name>{{packageName}}</Name>
</ProjectReference>
</ItemGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets'))" />
</Target>
</Project>

View File

@@ -3,6 +3,8 @@
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TargetFramework>{{targetFramework}}</TargetFramework>
<TargetFrameworkVersion>{{targetFrameworkVersion}}</TargetFrameworkVersion>
<TargetFrameworkIdentifier>{{targetFrameworkIdentifier}}</TargetFrameworkIdentifier>
<AssemblyName>{{packageName}}</AssemblyName>
<PackageId>{{packageName}}</PackageId>
<OutputType>Library</OutputType>

View File

@@ -23,8 +23,6 @@
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
</ItemGroup>
{{^netStandard}}

View File

@@ -245,7 +245,6 @@ namespace {{packageName}}.Client
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
var response = await RestClient.Execute{{^netStandard}}TaskAsync{{/netStandard}}(request);
InterceptResponse(request, response);

View File

@@ -23,7 +23,7 @@ const (
{{#enumVars}}
{{^-first}}
{{/-first}}
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = "{{{value}}}"
{{{classname.toUpperCase}}}_{{name}} {{{classname}}} = "{{{value}}}"
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}
@@ -36,7 +36,7 @@ type {{classname}} struct {
// {{{description}}}
{{/description}}
{{name}} *{{{dataType}}} `json:"{{baseName}},omitempty"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{#isNullable}} isExplicitNull{{name}} bool `json:"-"{{#withXml}} xml:"-"{{/withXml}}`{{/isNullable}}
{{#isNullable}} isExplicitNull{{name}} bool `json:"-"{{#withXml}} xml:"-"{{/withXml}}`{{/isNullable}}
{{/vars}}
}
{{/isEnum}}

View File

@@ -23,7 +23,7 @@ const (
{{#enumVars}}
{{^-first}}
{{/-first}}
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = "{{{value}}}"
{{{classname.toUpperCase}}}_{{name}} {{{classname}}} = "{{{value}}}"
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}

View File

@@ -54,29 +54,7 @@ Name | Type | Description | Notes
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}
{{#authMethods}}
{{#isApiKey}}
Configure {{name}}:
ApiClient.apiKey["{{keyParamName}}"] = ""
ApiClient.apiKeyPrefix["{{keyParamName}}"] = ""
{{/isApiKey}}
{{#isBasic}}
{{^isBasicBearer}}
Configure {{name}}:
ApiClient.username = ""
ApiClient.password = ""
{{/isBasicBearer}}
{{#isBasicBearer}}
Configure {{name}}:
ApiClient.accessToken = ""
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
Configure {{name}}:
ApiClient.accessToken = ""
{{/isOAuth}}
{{/authMethods}}
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers

View File

@@ -15,18 +15,11 @@ 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<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
@@ -72,61 +65,8 @@ open class ApiClient(val baseUrl: String) {
}
}
{{#hasAuthMethods}}
protected fun updateAuthParams(requestConfig: RequestConfig) {
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInHeader}}
if (requestConfig.headers["{{keyParamName}}"].isNullOrEmpty()) {
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (requestConfig.query["{{keyParamName}}"].isNullOrEmpty()) {
{{/isKeyInQuery}}
if (apiKeyPrefix["{{keyParamName}}"] != null) {
{{#isKeyInHeader}}
requestConfig.headers["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"] + " " + apiKey["{{keyParamName}}"]
{{/isKeyInHeader}}
{{#isKeyInQuery}}
requestConfig.query["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"] + " " + apiKey["{{keyParamName}}"]
{{/isKeyInQuery}}
} else {
{{#isKeyInHeader}}
requestConfig.headers["{{keyParamName}}"] = apiKey["{{keyParamName}}"]
{{/isKeyInHeader}}
{{#isKeyInQuery}}
requestConfig.query["{{keyParamName}}"] = apiKey["{{keyParamName}}"]
{{/isKeyInQuery}}
}
}
{{/isApiKey}}
{{#isBasic}}
{{^isBasicBearer}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = Credentials.basic(username, password)
}
{{/isBasicBearer}}
{{#isBasicBearer}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = "Bearer " + accessToken
}
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = "Bearer " + accessToken
}
{{/isOAuth}}
{{/authMethods}}
}
{{/hasAuthMethods}}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
{{#hasAuthMethods}}
// take authMethod from operation
updateAuthParams(requestConfig)
{{/hasAuthMethods}}
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))

View File

@@ -16,7 +16,7 @@ def _deserialize(data, klass):
if data is None:
return None
if klass in six.integer_types or klass in (float, str, bool, bytearray):
if klass in six.integer_types or klass in (float, str, bool):
return _deserialize_primitive(data, klass)
elif klass == object:
return _deserialize_object(data)

View File

@@ -95,14 +95,7 @@ Name | Type | Description | Notes
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{#responses.0}}
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
{{#responses}}
| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} |
{{/responses}}
{{/responses.0}}
{{/operation}}
{{/operations}}

View File

@@ -13,31 +13,16 @@ import {
{{/imports.0}}
{{#operations}}
{{#namespaceParameterInterfaces}}
{{#operation.0}}
/**
* Generated request parameter interface declarations (in namespace to avoid collisions).
*/
export namespace {{baseName}}Requests {
{{/operation.0}}
{{/namespaceParameterInterfaces}}
{{#operation}}
{{#allParams.0}}
{{paramIfaceIndent}}export interface {{operationIdCamelCase}}{{paramIfaceSuffix}} {
{{#allParams}}
{{paramIfaceIndent}} {{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}};
{{/allParams}}
{{paramIfaceIndent}}}
export interface {{operationIdCamelCase}}Request {
{{#allParams}}
{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}};
{{/allParams}}
}
{{/allParams.0}}
{{/operation}}
{{#namespaceParameterInterfaces}}
{{#operation.0}}
}
{{/operation.0}}
{{/namespaceParameterInterfaces}}
{{/operations}}
{{#operations}}
/**
@@ -54,7 +39,7 @@ export class {{classname}} extends runtime.BaseAPI {
* {{&summary}}
{{/summary}}
*/
async {{nickname}}Raw({{#allParams.0}}requestParameters: {{paramIfaceNsPrefix}}{{operationIdCamelCase}}{{paramIfaceSuffix}}{{/allParams.0}}): Promise<runtime.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> {
async {{nickname}}Raw({{#allParams.0}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Promise<runtime.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> {
{{#allParams}}
{{#required}}
if (requestParameters.{{paramName}} === null || requestParameters.{{paramName}} === undefined) {
@@ -264,7 +249,7 @@ export class {{classname}} extends runtime.BaseAPI {
}
{{/useSingleRequestParameter}}
{{#useSingleRequestParameter}}
async {{nickname}}({{#allParams.0}}requestParameters: {{paramIfaceNsPrefix}}{{operationIdCamelCase}}{{paramIfaceSuffix}}{{/allParams.0}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
async {{nickname}}({{#allParams.0}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
{{#returnType}}
const response = await this.{{nickname}}Raw({{#allParams.0}}requestParameters{{/allParams.0}});
return await response.value();

View File

@@ -804,42 +804,4 @@ public class InlineModelResolverTest {
Schema nullableRequestBodySchema = ModelUtils.getReferencedSchema(openAPI, nullableRequestBodyReference);
assertTrue(nullableRequestBodySchema.getNullable());
}
@Test
public void callbacks() {
OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
new InlineModelResolver().flatten(openAPI);
RequestBody callbackRequestBodyReference = openAPI
.getPaths()
.get("/callback")
.getPost()
.getCallbacks()
.get("webhook")
.get("{$request.body#/callbackUri}")
.getPost()
.getRequestBody();
assertNotNull(callbackRequestBodyReference.get$ref());
RequestBody resolvedCallbackRequestBody = openAPI
.getComponents()
.getRequestBodies()
.get(ModelUtils.getSimpleRef(callbackRequestBodyReference.get$ref()));
Schema callbackRequestSchemaReference = resolvedCallbackRequestBody
.getContent()
.get("application/json")
.getSchema();
assertNotNull(callbackRequestSchemaReference.get$ref());
Schema resolvedCallbackSchema = openAPI
.getComponents()
.getSchemas()
.get(ModelUtils.getSimpleRef(callbackRequestSchemaReference.get$ref()));
Map properties = resolvedCallbackSchema.getProperties();
assertTrue(properties.get("notificationId") instanceof StringSchema);
assertTrue(properties.get("action") instanceof StringSchema);
assertTrue(properties.get("data") instanceof StringSchema);
}
}

View File

@@ -1,12 +1,8 @@
package org.openapitools.codegen;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -70,38 +66,19 @@ public class TestUtils {
File file = new File(root, filename);
String absoluteFilename = file.getAbsolutePath().replace("\\", "/");
if (!generatedFiles.containsKey(absoluteFilename)) {
fail("Could not find '" + absoluteFilename + "' file in list:\n" +
Assert.fail("Could not find '" + absoluteFilename + "' file in list:\n" +
generatedFiles.keySet().stream().sorted().collect(Collectors.joining(",\n")));
}
assertTrue(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was not found in the list of generated files");
assertTrue(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was not fould in the list of generated files");
}
public static void ensureDoesNotContainsFile(Map<String, String> generatedFiles, File root, String filename) {
File file = new File(root, filename);
String absoluteFilename = file.getAbsolutePath().replace("\\", "/");
if (generatedFiles.containsKey(absoluteFilename)) {
fail("File '" + absoluteFilename + "' exists in file in list:\n" +
Assert.fail("File '" + absoluteFilename + "' exists in file in list:\n" +
generatedFiles.keySet().stream().sorted().collect(Collectors.joining(",\n")));
}
assertFalse(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was found in the list of generated files");
}
public static void validateJavaSourceFiles(Map<String, String> fileMap) {
fileMap.forEach( (fileName, fileContents) -> {
if (fileName.endsWith(".java")) {
assertValidJavaSourceCode(fileContents, fileName);
}
}
);
}
public static void assertValidJavaSourceCode(String javaSourceCode, String filename) {
try {
CompilationUnit compilation = StaticJavaParser.parse(javaSourceCode);
assertTrue(compilation.getTypes().size() > 0, "File: " + filename);
}
catch (ParseProblemException ex) {
fail("Java parse problem: " + filename, ex);
}
assertFalse(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was fould in the list of generated files");
}
}

View File

@@ -50,8 +50,6 @@ public class GoClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setWithXml(GoClientOptionsProvider.WITH_XML_VALUE);
times = 1;
clientCodegen.setWithXml(GoClientOptionsProvider.ENUM_CLASS_PREFIX_VALUE);
times = 1;
clientCodegen.setPrependFormOrBodyParameters(Boolean.valueOf(GoClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE));
times = 1;
clientCodegen.setIsGoSubmodule(Boolean.valueOf(GoClientOptionsProvider.IS_GO_SUBMODULE_VALUE));

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen.java;
import static org.openapitools.codegen.TestUtils.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@@ -319,8 +318,6 @@ public class JavaClientCodegenTest {
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/java/xyz/abcdef/StringUtil.java");
TestUtils.ensureContainsFile(generatedFiles, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java");
validateJavaSourceFiles(generatedFiles);
String defaultApiFilename = new File(output, "src/main/java/xyz/abcdef/api/DefaultApi.java").getAbsolutePath().replace("\\", "/");
String defaultApiConent = generatedFiles.get(defaultApiFilename);
assertTrue(defaultApiConent.contains("public class DefaultApi"));

View File

@@ -23,8 +23,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles;
/**
* Unit-Test for {@link org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen}.
*
@@ -206,7 +204,6 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/openapi/openapi.yaml");
output.deleteOnExit();
@@ -231,7 +228,6 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureDoesNotContainsFile(generatedFiles, output, "src/main/openapi/openapi.yaml");
output.deleteOnExit();
@@ -256,7 +252,6 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/resources/META-INF/openapi.yaml");
output.deleteOnExit();
@@ -281,7 +276,6 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "openapi.yml");
output.deleteOnExit();

View File

@@ -28,7 +28,6 @@ public class GoClientOptionsProvider implements OptionsProvider {
public static final String PACKAGE_NAME_VALUE = "Go";
public static final boolean WITH_GO_CODEGEN_COMMENT_VALUE = true;
public static final boolean WITH_XML_VALUE = true;
public static final boolean ENUM_CLASS_PREFIX_VALUE = true;
public static final Boolean PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = true;
public static final boolean IS_GO_SUBMODULE_VALUE = true;
@@ -46,7 +45,6 @@ public class GoClientOptionsProvider implements OptionsProvider {
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
.put(CodegenConstants.WITH_GO_CODEGEN_COMMENT, "true")
.put(CodegenConstants.WITH_XML, "true")
.put(CodegenConstants.ENUM_CLASS_PREFIX, "true")
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true")
.put(CodegenConstants.IS_GO_SUBMODULE, "true")
.build();

View File

@@ -52,7 +52,6 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider {
.put(TypeScriptFetchClientCodegen.SNAPSHOT, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.USE_SINGLE_REQUEST_PARAMETER, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.NAMESPACE_PARAMETER_INTERFACES, Boolean.FALSE.toString())
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.build();

View File

@@ -293,40 +293,6 @@ paths:
responses:
'200':
description: OK
/callback:
post:
requestBody:
content:
application/json:
schema:
type: object
properties:
callbackUri:
type: string
responses:
201:
headers:
Location:
description: Contains the URI of the newly created resource
schema:
type: string
callbacks:
webhook:
'{$request.body#/callbackUri}':
post:
operationId: webhookNotify
requestBody:
content:
application/json:
schema:
type: object
properties:
notificationId:
type: string
action:
type: string
data:
type: string
components:
schemas:
Users:

28
pom.xml
View File

@@ -188,7 +188,7 @@
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@@ -843,18 +843,6 @@
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>
</modules>
</profile>
<profile>
<id>typescript-fetch-client-builds-namespace-parameter-interfaces</id>
<activation>
<property>
<name>env</name>
<value>java</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/typescript-fetch/builds/namespace-parameter-interfaces</module>
</modules>
</profile>
<profile>
<id>typescript-angularjs-client</id>
<activation>
@@ -1037,6 +1025,9 @@
<!-- clients -->
<module>samples/client/petstore/c</module>
<module>samples/client/petstore/cpp-qt5</module>
<!--<module>samples/client/petstore/dart-jaguar/openapi</module>
<module>samples/client/petstore/dart-jaguar/flutter_petstore/openapi</module>-->
<!--<module>samples/client/petstore/dart2/petstore</module>-->
<module>samples/client/petstore/elm-0.18</module>
<module>samples/client/petstore/rust</module>
<module>samples/client/petstore/rust-reqwest</module>
@@ -1059,8 +1050,7 @@
<module>samples/client/petstore/typescript-fetch/builds/es6-target</module>
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>
<module>samples/client/petstore/typescript-fetch/tests/default</module>
<!-- comment out due to CI failure, e.g. https://travis-ci.org/OpenAPITools/openapi-generator/builds/574865730
<module>samples/client/petstore/typescript-axios/tests/default</module>-->
<module>samples/client/petstore/typescript-axios/tests/default</module>
<module>samples/client/petstore/typescript-node/npm</module>
<module>samples/client/petstore/typescript-rxjs/builds/with-npm-version</module>
<!-- comment out due to github rate limit error
@@ -1243,9 +1233,9 @@
<module>samples/client/petstore/elixir</module>
<module>samples/client/petstore/erlang-client</module>
<module>samples/client/petstore/erlang-proper</module>
<!--<module>samples/client/petstore/kotlin/</module>
<module>samples/client/petstore/kotlin/</module>
<module>samples/client/petstore/kotlin-threetenbp/</module>
<module>samples/client/petstore/kotlin-string/</module>-->
<module>samples/client/petstore/kotlin-string/</module>
<!-- servers -->
<module>samples/server/petstore/erlang-server</module>
<module>samples/server/petstore/jaxrs/jersey2</module>
@@ -1395,8 +1385,8 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<swagger-parser-groupid>org.openapitools.swagger.parser</swagger-parser-groupid>
<swagger-core-version>2.0.9</swagger-core-version>
<swagger-parser-version>2.0.14-OpenAPITools.org-1</swagger-parser-version>
<swagger-parser-version>2.0.13-OpenAPITools.org-2</swagger-parser-version>
<swagger-core-version>2.0.7</swagger-core-version>
<scala-version>2.11.1</scala-version>
<felix-version>3.3.1</felix-version>
<commons-io-version>2.4</commons-io-version>

View File

@@ -51,10 +51,7 @@ void (empty response body)
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
# **DeletePet**
> DeletePet(pet.id, api.key=var.api.key)
@@ -95,10 +92,7 @@ void (empty response body)
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid pet value | - |
# **FindPetsByStatus**
> array[Pet] FindPetsByStatus(status)
@@ -140,11 +134,7 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid status value | - |
# **FindPetsByTags**
> array[Pet] FindPetsByTags(tags)
@@ -186,11 +176,7 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid tag value | - |
# **GetPetById**
> Pet GetPetById(pet.id)
@@ -232,12 +218,7 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
# **UpdatePet**
> UpdatePet(body)
@@ -276,12 +257,7 @@ void (empty response body)
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
| **405** | Validation exception | - |
# **UpdatePetWithForm**
> UpdatePetWithForm(pet.id, name=var.name, status=var.status)
@@ -324,10 +300,7 @@ void (empty response body)
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
# **UploadFile**
> ModelApiResponse UploadFile(pet.id, additional.metadata=var.additional.metadata, file=var.file)
@@ -371,8 +344,5 @@ Name | Type | Description | Notes
- **Content-Type**: multipart/form-data
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |

View File

@@ -47,11 +47,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
# **GetInventory**
> map(integer) GetInventory()
@@ -89,10 +85,7 @@ This endpoint does not need any parameter.
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
# **GetOrderById**
> Order GetOrderById(order.id)
@@ -132,12 +125,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
# **PlaceOrder**
> Order PlaceOrder(body)
@@ -175,9 +163,5 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Order | - |

View File

@@ -51,10 +51,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **CreateUsersWithArrayInput**
> CreateUsersWithArrayInput(body)
@@ -91,10 +88,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **CreateUsersWithListInput**
> CreateUsersWithListInput(body)
@@ -131,10 +125,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **DeleteUser**
> DeleteUser(username)
@@ -173,11 +164,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
# **GetUserByName**
> User GetUserByName(username)
@@ -215,12 +202,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
# **LoginUser**
> character LoginUser(username, password)
@@ -260,11 +242,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user <br> * X-Expires-After - date in UTC when toekn expires <br> |
| **400** | Invalid username/password supplied | - |
# **LogoutUser**
> LogoutUser()
@@ -297,10 +275,7 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **UpdateUser**
> UpdateUser(username, body)
@@ -341,9 +316,5 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid user supplied | - |
| **404** | User not found | - |

View File

@@ -1,7 +1,15 @@
#include "PetApiTests.h"
#include <QTest>
#include <QTimer>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
PetApiTests::PetApiTests () {}
PetApiTests::~PetApiTests () {
}
OAIPetApi* PetApiTests::getApi() {
auto api = new OAIPetApi();
@@ -12,65 +20,96 @@ OAIPetApi* PetApiTests::getApi() {
OAIPet PetApiTests::createRandomPet() {
OAIPet pet;
qint64 id = QDateTime::currentMSecsSinceEpoch();
pet.setName("monster");
pet.setName(QString("monster"));
pet.setId(id);
pet.setStatus("freaky");
pet.setStatus(QString("freaky"));
return pet;
}
void PetApiTests::runTests() {
PetApiTests* tests = new PetApiTests();
QTest::qExec(tests);
delete tests;
}
void PetApiTests::findPetsByStatusTest() {
OAIPetApi* api = getApi();
QEventLoop loop;
bool petFound = false;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
connect(api, &OAIPetApi::findPetsByStatusSignal, [&](QList<OAIPet> pets) {
petFound = true;
auto validator = [this](QList<OAIPet> pets) {
foreach(OAIPet pet, pets) {
QVERIFY(pet.getStatus().startsWith("available") || pet.getStatus().startsWith("sold"));
}
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::findPetsByStatusSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->findPetsByStatus({"available", "sold"});
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
QList<QString> status;
QString available("available");
QString sold("sold");
status.append(available);
status.append(sold);
api->findPetsByStatus(status);
timer.start();
loop.exec();
QVERIFY2(petFound, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void PetApiTests::createAndGetPetTest() {
OAIPetApi* api = getApi();
QEventLoop loop;
bool petCreated = false;
connect(api, &OAIPetApi::addPetSignal, [&]() {
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this]() {
// pet created
petCreated = true;
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
OAIPet pet = createRandomPet();
qint64 id = pet.getId();
api->addPet(pet);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petCreated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
bool petFetched = false;
timer.setInterval(1000);
timer.setSingleShot(true);
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
auto getPetValidator = [this](OAIPet pet) {
QVERIFY(pet.getId() > 0);
QVERIFY(pet.getStatus().compare("freaky") == 0);
loop.quit();
petFetched = true;
});
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, getPetValidator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getPetById(id);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
@@ -81,61 +120,76 @@ void PetApiTests::updatePetTest() {
OAIPet petToCheck;
qint64 id = pet.getId();
QEventLoop loop;
bool petAdded = false;
QTimer timer;
timer.setInterval(100000);
timer.setSingleShot(true);
connect(api, &OAIPetApi::addPetSignal, [&](){
petAdded = true;
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
// create pet
api->addPet(pet);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petAdded, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// fetch it
timer.setInterval(1000);
timer.setSingleShot(true);
bool petFetched = false;
connect(api, &OAIPetApi::getPetByIdSignal, this, [&](OAIPet pet) {
petFetched = true;
petToCheck = pet;
loop.quit();
});
auto fetchPet = [&](OAIPet pet) {
petToCheck = pet;
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
// create pet
api->getPetById(id);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// update it
bool petUpdated = false;
connect(api, &OAIPetApi::updatePetSignal, [&]() {
petUpdated = true;
loop.quit();
});
timer.setInterval(1000);
timer.setSingleShot(true);
auto updatePetTest = [this]() {
emit quit();
};
connect(api, &OAIPetApi::updatePetSignal, this, updatePetTest);
connect(&timer, &QTimer::timeout, &loop, finalizer);
// update pet
petToCheck.setStatus(QString("scary"));
api->updatePet(petToCheck);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petUpdated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// check it
bool petFetched2 = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petFetched2 = true;
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchPet2 = [&](OAIPet pet) {
QVERIFY(pet.getId() == petToCheck.getId());
QVERIFY(pet.getStatus().compare(petToCheck.getStatus()) == 0);
loop.quit();
});
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet2);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getPetById(id);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petFetched2, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
@@ -146,57 +200,70 @@ void PetApiTests::updatePetWithFormTest() {
OAIPet petToCheck;
qint64 id = pet.getId();
QEventLoop loop;
QTimer timer;
// create pet
bool petAdded = false;
connect(api, &OAIPetApi::addPetSignal, [&](){
petAdded = true;
loop.quit();
});
timer.setInterval(1000);
timer.setSingleShot(true);
auto validator = [this ]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->addPet(pet);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petAdded, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// fetch it
bool petFetched = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petFetched = true;
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchPet = [&](OAIPet pet) {
petToCheck = pet;
loop.quit();
});
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getPetById(id);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// update it
bool petUpdated = false;
connect(api, &OAIPetApi::updatePetWithFormSignal, [&](){
petUpdated = true;
loop.quit();
});
timer.setInterval(1000);
timer.setSingleShot(true);
connect(api, &OAIPetApi::updatePetWithFormSignal, this, [this](){emit quit();});
connect(&timer, &QTimer::timeout, &loop, finalizer);
QString name("gorilla");
api->updatePetWithForm(id, name, nullptr);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petUpdated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
// fetch it
bool petUpdated2 = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petUpdated2 = true;
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchUpdatedPet = [this](OAIPet pet) {
QVERIFY(pet.getName().compare(QString("gorilla")) == 0);
loop.quit();
});
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchUpdatedPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getPetById(id);
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(petUpdated2, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}

View File

@@ -1,18 +1,34 @@
#pragma once
#ifndef PETAPITESTS_H
#define PETAPITESTS_H
#include <QtTest/QtTest>
#include <QTimer>
#include "../client/OAIPetApi.h"
using namespace OpenAPI;
class PetApiTests: public QObject {
Q_OBJECT
Q_OBJECT
public:
PetApiTests();
virtual ~PetApiTests();
static void runTests();
private:
OAIPetApi* getApi();
OAIPet createRandomPet();
signals:
void quit();
bool success();
private slots:
void findPetsByStatusTest();
void createAndGetPetTest();
void updatePetTest();
void updatePetWithFormTest();
};
#endif // PETAPITESTS_H

View File

@@ -1,85 +1,117 @@
#include "StoreApiTests.h"
#include <QTest>
#include <QTimer>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
StoreApiTests::StoreApiTests () {}
StoreApiTests::~StoreApiTests () {
}
OAIStoreApi* StoreApiTests::getApi() {
auto api = new OAIStoreApi();
api->setHost("http://petstore.swagger.io");
return api;
}
void StoreApiTests::runTests() {
StoreApiTests* tests = new StoreApiTests();
QTest::qExec(tests);
delete tests;
}
void StoreApiTests::placeOrderTest() {
auto api = getApi();
QEventLoop loop;
bool orderPlaced = false;
connect(api, &OAIStoreApi::placeOrderSignal, [&](OAIOrder order) {
orderPlaced = true;
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this](OAIOrder order) {
QVERIFY(order.getPetId() == 10000);
QVERIFY((order.getId() == 500));
qDebug() << order.getShipDate();
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
connect(api, &OAIStoreApi::placeOrderSignalE, [&](){
QFAIL("shouldn't trigger error");
loop.quit();
});
};
connect(this, &StoreApiTests::quit, finalizer);
connect(api, &OAIStoreApi::placeOrderSignal, this, validator);
connect(api, &OAIStoreApi::placeOrderSignalE, this, finalizer);
connect(&timer, &QTimer::timeout, &loop, finalizer);
OAIOrder order;
order.setId(500);
order.setQuantity(10);
order.setPetId(10000);
order.setComplete(false);
order.setStatus("shipping");
order.setStatus(QString("shipping"));
order.setShipDate(QDateTime::currentDateTime());
api->placeOrder(order);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(orderPlaced, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void StoreApiTests::getOrderByIdTest() {
auto api = getApi();
QEventLoop loop;
bool orderFetched = false;
connect(api, &OAIStoreApi::getOrderByIdSignal, [&](OAIOrder order) {
orderFetched = true;
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this](OAIOrder order) {
QVERIFY(order.getPetId() == 10000);
QVERIFY((order.getId() == 500));
qDebug() << order.getShipDate();
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &StoreApiTests::quit, finalizer);
connect(api, &OAIStoreApi::getOrderByIdSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getOrderById(500);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(orderFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void StoreApiTests::getInventoryTest() {
auto api = getApi();
QEventLoop loop;
bool inventoryFetched = false;
connect(api, &OAIStoreApi::getInventorySignal, [&](QMap<QString, qint32> status) {
inventoryFetched = true;
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this](QMap<QString, qint32> status) {
for(const auto& key : status.keys()) {
qDebug() << (key) << " Quantities " << status.value(key);
}
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &StoreApiTests::quit, finalizer);
connect(api, &OAIStoreApi::getInventorySignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getInventory();
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(inventoryFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}

View File

@@ -1,16 +1,30 @@
#pragma once
#ifndef STOREAPITESTS_H
#define STOREAPITESTS_H
#include <QtTest/QtTest>
#include <QTimer>
#include "../client/OAIStoreApi.h"
using namespace OpenAPI;
class StoreApiTests: public QObject {
Q_OBJECT
Q_OBJECT
public:
StoreApiTests();
virtual ~StoreApiTests();
static void runTests();
private:
OAIStoreApi* getApi();
signals:
void quit();
bool success();
private slots:
void placeOrderTest();
void getOrderByIdTest();
void getInventoryTest();
};
#endif // STOREAPITESTS_H

View File

@@ -1,24 +1,38 @@
#include "UserApiTests.h"
#include <QTest>
#include <QTimer>
#include <stdlib.h>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
UserApiTests::UserApiTests () {}
UserApiTests::~UserApiTests () {
exit(0);
}
OAIUserApi* UserApiTests::getApi() {
auto api = new OAIUserApi();
api->setHost("http://petstore.swagger.io");
return api;
}
void UserApiTests::runTests() {
UserApiTests* tests = new UserApiTests();
QTest::qExec(tests);
delete tests;
}
OAIUser UserApiTests::createRandomUser() {
OAIUser user;
user.setId(QDateTime::currentMSecsSinceEpoch());
user.setEmail("Jane.Doe@openapitools.io");
user.setFirstName("Jane");
user.setLastName("Doe");
user.setPhone("123456789");
user.setUsername("janedoe");
user.setPassword("secretPassword");
user.setEmail(QString("Jane.Doe@openapitools.io"));
user.setFirstName(QString("Jane"));
user.setLastName(QString("Doe"));
user.setPhone(QString("123456789"));
user.setUsername(QString("janedoe"));
user.setPassword(QString("secretPassword"));
user.setUserStatus(static_cast<int>(rand()));
return user;
}
@@ -26,160 +40,213 @@ OAIUser UserApiTests::createRandomUser() {
void UserApiTests::createUserTest(){
auto api = getApi();
QEventLoop loop;
bool userCreated = false;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::createUserSignal, [&](){
userCreated = true;
loop.quit();
});
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::createUserSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->createUser(createRandomUser());
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(userCreated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::createUsersWithArrayInputTest(){
auto api = getApi();
QEventLoop loop;
bool usersCreated = false;
connect(api, &OAIUserApi::createUsersWithArrayInputSignal, [&](){
usersCreated = true;
loop.quit();
});
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::createUsersWithArrayInputSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
QList<OAIUser> users;
users.append(createRandomUser());
users.append(createRandomUser());
users.append(createRandomUser());
api->createUsersWithArrayInput(users);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(usersCreated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::createUsersWithListInputTest(){
auto api = getApi();
QEventLoop loop;
bool usersCreated = false;
connect(api, &OAIUserApi::createUsersWithListInputSignal, [&](){
usersCreated = true;
loop.quit();
});
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::createUsersWithListInputSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
QList<OAIUser> users;
auto johndoe = createRandomUser();
johndoe.setUsername("johndoe");
johndoe.setUsername(QString("johndoe"));
auto rambo = createRandomUser();
rambo.setUsername("rambo");
rambo.setUsername(QString("rambo"));
users.append(johndoe);
users.append(rambo);
users.append(createRandomUser());
api->createUsersWithListInput(users);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(usersCreated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::deleteUserTest(){
auto api = getApi();
QEventLoop loop;
bool userDeleted = false;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::deleteUserSignal, [&](){
userDeleted = true;
loop.quit();
});
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::deleteUserSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->deleteUser("rambo");
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
api->deleteUser(QString("rambo"));
timer.start();
loop.exec();
QVERIFY2(userDeleted, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::getUserByNameTest(){
auto api = getApi();
QEventLoop loop;
bool userFetched = false;
QTimer timer;
timer.setInterval(30000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::getUserByNameSignal, [&](OAIUser summary) {
userFetched = true;
auto validator = [this](OAIUser summary) {
qDebug() << summary.getUsername();
QVERIFY(summary.getUsername() == "johndoe");
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::getUserByNameSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->getUserByName("johndoe");
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
api->getUserByName(QString("johndoe"));
timer.start();
loop.exec();
QVERIFY2(userFetched, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::loginUserTest(){
auto api = getApi();
QEventLoop loop;
bool userLogged = false;
QTimer timer;
timer.setInterval(30000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::loginUserSignal, [&](QString summary) {
userLogged = true;
auto validator = [this](QString summary) {
qDebug() << summary;
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::loginUserSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->loginUser("johndoe", "123456789");
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
api->loginUser(QString("johndoe"), QString("123456789"));
timer.start();
loop.exec();
QVERIFY2(userLogged, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::logoutUserTest(){
auto api = getApi();
QEventLoop loop;
bool userLoggedOut = false;
QTimer timer;
timer.setInterval(30000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::logoutUserSignal, [&](){
userLoggedOut = true;
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
});
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::logoutUserSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
api->logoutUser();
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
QVERIFY2(userLoggedOut, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}
void UserApiTests::updateUserTest(){
auto api = getApi();
QEventLoop loop;
bool userUpdated = false;
QTimer timer;
timer.setInterval(30000);
timer.setSingleShot(true);
connect(api, &OAIUserApi::updateUserSignal, [&]() {
userUpdated = true;
loop.quit();
});
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &UserApiTests::quit, finalizer);
connect(api, &OAIUserApi::updateUserSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
auto johndoe = createRandomUser();
johndoe.setUsername("johndoe");
api->updateUser("johndoe", johndoe);
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
johndoe.setUsername(QString("johndoe"));
api->updateUser(QString("johndoe"), johndoe);
timer.start();
loop.exec();
QVERIFY2(userUpdated, "didn't finish within timeout");
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
delete api;
}

View File

@@ -1,15 +1,28 @@
#pragma once
#ifndef USERAPITESTS_H
#define USERAPITESTS_H
#include <QtTest/QtTest>
#include <QTimer>
#include "../client/OAIUserApi.h"
using namespace OpenAPI;
class UserApiTests: public QObject {
Q_OBJECT
Q_OBJECT
public:
UserApiTests();
virtual ~UserApiTests();
static void runTests();
private:
OAIUserApi* getApi();
OAIUser createRandomUser();
signals:
void quit();
bool success();
private slots:
void createUserTest();
void createUsersWithArrayInputTest();
@@ -20,3 +33,5 @@ private slots:
void logoutUserTest();
void updateUserTest();
};
#endif // USERAPITESTS_H

View File

@@ -1,20 +1,12 @@
#include <QCoreApplication>
#include <QTest>
#include "PetApiTests.h"
#include "StoreApiTests.h"
#include "UserApiTests.h"
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
PetApiTests petApiTests;
StoreApiTests storeApiTests;
UserApiTests userApiTests;
int failedTests = 0;
failedTests += QTest::qExec(&petApiTests);
failedTests += QTest::qExec(&storeApiTests);
failedTests += QTest::qExec(&userApiTests);
return failedTests;
PetApiTests::runTests();
StoreApiTests::runTests();
UserApiTests::runTests();
return a.exec();
}

View File

@@ -4,8 +4,9 @@ set -e
mkdir build
cd build
# project
qmake ../PetStore/PetStore.pro
make
./PetStore

View File

@@ -30,26 +30,6 @@ namespace Org.OpenAPITools.Client
#endregion Private Fields
#region Constructors
/// <summary>
/// Empty Constructor.
/// </summary>
public Multimap()
{
_dictionary = new ConcurrentDictionary<T, IList<TValue>>();
}
/// <summary>
/// Constructor with comparer.
/// </summary>
/// <param name="comparer"></param>
public Multimap(IEqualityComparer<T> comparer) {
_dictionary = new ConcurrentDictionary<T, IList<TValue>>(comparer);
}
#endregion Constructors
#region Enumerators
/// <summary>

View File

@@ -19,7 +19,9 @@ The version of the OpenAPI document: 1.0.0
<RootNamespace>Org.OpenAPITools</RootNamespace>
<AssemblyName>Org.OpenAPITools</AssemblyName>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFramework>netstandard2.0</TargetFramework>
<!--<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>-->
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkIdentifier>.NETStandard</TargetFrameworkIdentifier>
<FileAlignment>512</FileAlignment>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml</DocumentationFile>
</PropertyGroup>
@@ -34,4 +36,6 @@ The version of the OpenAPI document: 1.0.0
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
</ItemGroup>
<Import Project="..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
</Project>

View File

@@ -30,26 +30,6 @@ namespace Org.OpenAPITools.Client
#endregion Private Fields
#region Constructors
/// <summary>
/// Empty Constructor.
/// </summary>
public Multimap()
{
_dictionary = new ConcurrentDictionary<T, IList<TValue>>();
}
/// <summary>
/// Constructor with comparer.
/// </summary>
/// <param name="comparer"></param>
public Multimap(IEqualityComparer<T> comparer) {
_dictionary = new ConcurrentDictionary<T, IList<TValue>>(comparer);
}
#endregion Constructors
#region Enumerators
/// <summary>

View File

@@ -3,6 +3,8 @@
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier>
<AssemblyName>Org.OpenAPITools</AssemblyName>
<PackageId>Org.OpenAPITools</PackageId>
<OutputType>Library</OutputType>

View File

@@ -202,7 +202,6 @@ namespace Org.OpenAPITools.Client
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
var response = await RestClient.ExecuteTaskAsync(request);
InterceptResponse(request, response);

View File

@@ -3,7 +3,7 @@
language: dart
dart:
# Install a specific stable release
- "1.24.3"
- "2.2.0"
install:
- pub get

View File

@@ -44,13 +44,13 @@ Please follow the [installation procedure](#installation--usage) and then run th
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var body = new Pet(); // Pet | Pet object that needs to be added to the store
var api_instance = PetApi();
var pet = Pet(); // Pet | Pet object that needs to be added to the store
try {
api_instance.addPet(body);
api_instance.addPet(pet);
} catch (e) {
print("Exception when calling PetApi->addPet: $e\n");
}
@@ -89,6 +89,8 @@ 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)
@@ -104,6 +106,12 @@ Class | Method | HTTP request | Description
- **API key parameter name**: api_key
- **Location**: HTTP header
## auth_cookie
- **Type**: API key
- **API key parameter name**: AUTH_KEY
- **Location**:
## petstore_auth
- **Type**: OAuth

View File

@@ -20,7 +20,7 @@ Method | HTTP request | Description
# **addPet**
> addPet(body)
> addPet(pet)
Add a new pet to the store
@@ -28,13 +28,13 @@ Add a new pet to the store
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var body = new Pet(); // Pet | Pet object that needs to be added to the store
var api_instance = PetApi();
var pet = Pet(); // Pet | Pet object that needs to be added to the store
try {
api_instance.addPet(body);
api_instance.addPet(pet);
} catch (e) {
print("Exception when calling PetApi->addPet: $e\n");
}
@@ -44,7 +44,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
**pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
@@ -70,9 +70,9 @@ Deletes a pet
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var api_instance = PetApi();
var petId = 789; // int | Pet id to delete
var apiKey = apiKey_example; // String |
@@ -116,9 +116,9 @@ Multiple status values can be provided with comma separated strings
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var api_instance = PetApi();
var status = []; // List<String> | Status values that need to be considered for filter
try {
@@ -161,9 +161,9 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var api_instance = PetApi();
var tags = []; // List<String> | Tags to filter by
try {
@@ -206,11 +206,11 @@ Returns a single pet
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: api_key
//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY';
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer";
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKeyPrefix = 'Bearer';
var api_instance = new PetApi();
var api_instance = PetApi();
var petId = 789; // int | ID of pet to return
try {
@@ -243,7 +243,7 @@ Name | Type | Description | Notes
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **updatePet**
> updatePet(body)
> updatePet(pet)
Update an existing pet
@@ -251,13 +251,13 @@ Update an existing pet
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var body = new Pet(); // Pet | Pet object that needs to be added to the store
var api_instance = PetApi();
var pet = Pet(); // Pet | Pet object that needs to be added to the store
try {
api_instance.updatePet(body);
api_instance.updatePet(pet);
} catch (e) {
print("Exception when calling PetApi->updatePet: $e\n");
}
@@ -267,7 +267,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
**pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
@@ -293,9 +293,9 @@ Updates a pet in the store with form data
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var api_instance = PetApi();
var petId = 789; // int | ID of pet that needs to be updated
var name = name_example; // String | Updated name of the pet
var status = status_example; // String | Updated status of the pet
@@ -339,9 +339,9 @@ uploads an image
```dart
import 'package:openapi/api.dart';
// TODO Configure OAuth2 access token for authorization: petstore_auth
//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN';
var api_instance = new PetApi();
var api_instance = PetApi();
var petId = 789; // int | ID of pet to update
var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
var file = BINARY_DATA_HERE; // MultipartFile | file to upload

View File

@@ -26,7 +26,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non
```dart
import 'package:openapi/api.dart';
var api_instance = new StoreApi();
var api_instance = StoreApi();
var orderId = orderId_example; // String | ID of the order that needs to be deleted
try {
@@ -68,11 +68,11 @@ Returns a map of status codes to quantities
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: api_key
//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY';
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer";
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKeyPrefix = 'Bearer';
var api_instance = new StoreApi();
var api_instance = StoreApi();
try {
var result = api_instance.getInventory();
@@ -111,7 +111,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge
```dart
import 'package:openapi/api.dart';
var api_instance = new StoreApi();
var api_instance = StoreApi();
var orderId = 789; // int | ID of pet that needs to be fetched
try {
@@ -144,7 +144,7 @@ No authorization required
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **placeOrder**
> Order placeOrder(body)
> Order placeOrder(order)
Place an order for a pet
@@ -152,11 +152,11 @@ Place an order for a pet
```dart
import 'package:openapi/api.dart';
var api_instance = new StoreApi();
var body = new Order(); // Order | order placed for purchasing the pet
var api_instance = StoreApi();
var order = Order(); // Order | order placed for purchasing the pet
try {
var result = api_instance.placeOrder(body);
var result = api_instance.placeOrder(order);
print(result);
} catch (e) {
print("Exception when calling StoreApi->placeOrder: $e\n");
@@ -167,7 +167,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Order**](Order.md)| order placed for purchasing the pet |
**order** | [**Order**](Order.md)| order placed for purchasing the pet |
### Return type
@@ -179,7 +179,7 @@ No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Content-Type**: application/json
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -20,7 +20,7 @@ Method | HTTP request | Description
# **createUser**
> createUser(body)
> createUser(user)
Create user
@@ -29,12 +29,16 @@ This can only be done by the logged in user.
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var body = new User(); // User | Created user object
var api_instance = UserApi();
var user = User(); // User | Created user object
try {
api_instance.createUser(body);
api_instance.createUser(user);
} catch (e) {
print("Exception when calling UserApi->createUser: $e\n");
}
@@ -44,7 +48,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**User**](User.md)| Created user object |
**user** | [**User**](User.md)| Created user object |
### Return type
@@ -52,29 +56,33 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
- **Content-Type**: Not defined
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **createUsersWithArrayInput**
> createUsersWithArrayInput(body)
> createUsersWithArrayInput(user)
Creates list of users with given input array
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var body = [new List&lt;User&gt;()]; // List<User> | List of user object
var api_instance = UserApi();
var user = [List&lt;User&gt;()]; // List<User> | List of user object
try {
api_instance.createUsersWithArrayInput(body);
api_instance.createUsersWithArrayInput(user);
} catch (e) {
print("Exception when calling UserApi->createUsersWithArrayInput: $e\n");
}
@@ -84,7 +92,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**List&lt;User&gt;**](User.md)| List of user object |
**user** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
@@ -92,29 +100,33 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
- **Content-Type**: Not defined
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **createUsersWithListInput**
> createUsersWithListInput(body)
> createUsersWithListInput(user)
Creates list of users with given input array
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var body = [new List&lt;User&gt;()]; // List<User> | List of user object
var api_instance = UserApi();
var user = [List&lt;User&gt;()]; // List<User> | List of user object
try {
api_instance.createUsersWithListInput(body);
api_instance.createUsersWithListInput(user);
} catch (e) {
print("Exception when calling UserApi->createUsersWithListInput: $e\n");
}
@@ -124,7 +136,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**List&lt;User&gt;**](User.md)| List of user object |
**user** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
@@ -132,11 +144,11 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
- **Content-Type**: Not defined
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
@@ -151,8 +163,12 @@ This can only be done by the logged in user.
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var api_instance = UserApi();
var username = username_example; // String | The name that needs to be deleted
try {
@@ -174,7 +190,7 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
@@ -192,7 +208,7 @@ Get user by user name
```dart
import 'package:openapi/api.dart';
var api_instance = new UserApi();
var api_instance = UserApi();
var username = username_example; // String | The name that needs to be fetched. Use user1 for testing.
try {
@@ -233,7 +249,7 @@ Logs user into the system
```dart
import 'package:openapi/api.dart';
var api_instance = new UserApi();
var api_instance = UserApi();
var username = username_example; // String | The user name for login
var password = password_example; // String | The password for login in clear text
@@ -275,8 +291,12 @@ Logs out current logged in user session
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var api_instance = UserApi();
try {
api_instance.logoutUser();
@@ -294,7 +314,7 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
@@ -304,7 +324,7 @@ No authorization required
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **updateUser**
> updateUser(username, body)
> updateUser(username, user)
Updated user
@@ -313,13 +333,17 @@ This can only be done by the logged in user.
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: auth_cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('auth_cookie').apiKeyPrefix = 'Bearer';
var api_instance = new UserApi();
var api_instance = UserApi();
var username = username_example; // String | name that need to be deleted
var body = new User(); // User | Updated user object
var user = User(); // User | Updated user object
try {
api_instance.updateUser(username, body);
api_instance.updateUser(username, user);
} catch (e) {
print("Exception when calling UserApi->updateUser: $e\n");
}
@@ -330,7 +354,7 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| name that need to be deleted | [default to null]
**body** | [**User**](User.md)| Updated user object |
**user** | [**User**](User.md)| Updated user object |
### Return type
@@ -338,11 +362,11 @@ void (empty response body)
### Authorization
No authorization required
[auth_cookie](../README.md#auth_cookie)
### HTTP request headers
- **Content-Type**: Not defined
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -18,10 +18,12 @@ part 'api/user_api.dart';
part 'model/api_response.dart';
part 'model/category.dart';
part 'model/inline_object.dart';
part 'model/inline_object1.dart';
part 'model/order.dart';
part 'model/pet.dart';
part 'model/tag.dart';
part 'model/user.dart';
ApiClient defaultApiClient = new ApiClient();
ApiClient defaultApiClient = ApiClient();

View File

@@ -10,12 +10,12 @@ class PetApi {
/// Add a new pet to the store
///
///
Future addPet(Pet body) async {
Object postBody = body;
Future addPet(Pet pet) async {
Object postBody = pet;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(pet == null) {
throw ApiException(400, "Missing required param: pet");
}
// create path and map variables
@@ -28,12 +28,12 @@ class PetApi {
List<String> contentTypes = ["application/json","application/xml"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -50,7 +50,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -60,11 +60,11 @@ class PetApi {
///
///
Future deletePet(int petId, { String apiKey }) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(petId == null) {
throw new ApiException(400, "Missing required param: petId");
throw ApiException(400, "Missing required param: petId");
}
// create path and map variables
@@ -78,12 +78,12 @@ class PetApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -100,7 +100,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -110,11 +110,11 @@ class PetApi {
///
/// Multiple status values can be provided with comma separated strings
Future<List<Pet>> findPetsByStatus(List<String> status) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(status == null) {
throw new ApiException(400, "Missing required param: status");
throw ApiException(400, "Missing required param: status");
}
// create path and map variables
@@ -128,12 +128,12 @@ class PetApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -150,7 +150,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return (apiClient.deserialize(_decodeBodyBytes(response), 'List<Pet>') as List).map((item) => item as Pet).toList();
} else {
@@ -161,11 +161,11 @@ class PetApi {
///
/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
Future<List<Pet>> findPetsByTags(List<String> tags) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(tags == null) {
throw new ApiException(400, "Missing required param: tags");
throw ApiException(400, "Missing required param: tags");
}
// create path and map variables
@@ -179,12 +179,12 @@ class PetApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -201,7 +201,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return (apiClient.deserialize(_decodeBodyBytes(response), 'List<Pet>') as List).map((item) => item as Pet).toList();
} else {
@@ -212,11 +212,11 @@ class PetApi {
///
/// Returns a single pet
Future<Pet> getPetById(int petId) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(petId == null) {
throw new ApiException(400, "Missing required param: petId");
throw ApiException(400, "Missing required param: petId");
}
// create path and map variables
@@ -229,12 +229,12 @@ class PetApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["api_key"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -251,7 +251,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet;
} else {
@@ -261,12 +261,12 @@ class PetApi {
/// Update an existing pet
///
///
Future updatePet(Pet body) async {
Object postBody = body;
Future updatePet(Pet pet) async {
Object postBody = pet;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(pet == null) {
throw ApiException(400, "Missing required param: pet");
}
// create path and map variables
@@ -279,12 +279,12 @@ class PetApi {
List<String> contentTypes = ["application/json","application/xml"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -301,7 +301,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -311,11 +311,11 @@ class PetApi {
///
///
Future updatePetWithForm(int petId, { String name, String status }) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(petId == null) {
throw new ApiException(400, "Missing required param: petId");
throw ApiException(400, "Missing required param: petId");
}
// create path and map variables
@@ -328,12 +328,12 @@ class PetApi {
List<String> contentTypes = ["application/x-www-form-urlencoded"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if (name != null) {
hasFields = true;
mp.fields['name'] = parameterToString(name);
@@ -362,7 +362,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -372,11 +372,11 @@ class PetApi {
///
///
Future<ApiResponse> uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(petId == null) {
throw new ApiException(400, "Missing required param: petId");
throw ApiException(400, "Missing required param: petId");
}
// create path and map variables
@@ -389,12 +389,12 @@ class PetApi {
List<String> contentTypes = ["multipart/form-data"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["petstore_auth"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if (additionalMetadata != null) {
hasFields = true;
mp.fields['additionalMetadata'] = parameterToString(additionalMetadata);
@@ -422,7 +422,7 @@ class PetApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse;
} else {

View File

@@ -11,11 +11,11 @@ class StoreApi {
///
/// For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
Future deleteOrder(String orderId) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(orderId == null) {
throw new ApiException(400, "Missing required param: orderId");
throw ApiException(400, "Missing required param: orderId");
}
// create path and map variables
@@ -28,12 +28,12 @@ class StoreApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = [];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -50,7 +50,7 @@ class StoreApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -60,7 +60,7 @@ class StoreApi {
///
/// Returns a map of status codes to quantities
Future<Map<String, int>> getInventory() async {
Object postBody = null;
Object postBody;
// verify required params are set
@@ -74,12 +74,12 @@ class StoreApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["api_key"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -96,9 +96,9 @@ class StoreApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return new Map<String, int>.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map<String, int>'));
return Map<String, int>.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map<String, int>'));
;
} else {
return null;
@@ -108,11 +108,11 @@ class StoreApi {
///
/// For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
Future<Order> getOrderById(int orderId) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(orderId == null) {
throw new ApiException(400, "Missing required param: orderId");
throw ApiException(400, "Missing required param: orderId");
}
// create path and map variables
@@ -125,12 +125,12 @@ class StoreApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = [];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -147,7 +147,7 @@ class StoreApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order;
} else {
@@ -157,12 +157,12 @@ class StoreApi {
/// Place an order for a pet
///
///
Future<Order> placeOrder(Order body) async {
Object postBody = body;
Future<Order> placeOrder(Order order) async {
Object postBody = order;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(order == null) {
throw ApiException(400, "Missing required param: order");
}
// create path and map variables
@@ -173,14 +173,14 @@ class StoreApi {
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
List<String> contentTypes = [];
List<String> contentTypes = ["application/json"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = [];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -197,7 +197,7 @@ class StoreApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order;
} else {

View File

@@ -10,12 +10,12 @@ class UserApi {
/// Create user
///
/// This can only be done by the logged in user.
Future createUser(User body) async {
Object postBody = body;
Future createUser(User user) async {
Object postBody = user;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(user == null) {
throw ApiException(400, "Missing required param: user");
}
// create path and map variables
@@ -26,14 +26,14 @@ class UserApi {
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
List<String> contentTypes = [];
List<String> contentTypes = ["application/json"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -50,7 +50,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -59,12 +59,12 @@ class UserApi {
/// Creates list of users with given input array
///
///
Future createUsersWithArrayInput(List<User> body) async {
Object postBody = body;
Future createUsersWithArrayInput(List<User> user) async {
Object postBody = user;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(user == null) {
throw ApiException(400, "Missing required param: user");
}
// create path and map variables
@@ -75,14 +75,14 @@ class UserApi {
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
List<String> contentTypes = [];
List<String> contentTypes = ["application/json"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -99,7 +99,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -108,12 +108,12 @@ class UserApi {
/// Creates list of users with given input array
///
///
Future createUsersWithListInput(List<User> body) async {
Object postBody = body;
Future createUsersWithListInput(List<User> user) async {
Object postBody = user;
// verify required params are set
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(user == null) {
throw ApiException(400, "Missing required param: user");
}
// create path and map variables
@@ -124,14 +124,14 @@ class UserApi {
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
List<String> contentTypes = [];
List<String> contentTypes = ["application/json"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -148,7 +148,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -158,11 +158,11 @@ class UserApi {
///
/// This can only be done by the logged in user.
Future deleteUser(String username) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(username == null) {
throw new ApiException(400, "Missing required param: username");
throw ApiException(400, "Missing required param: username");
}
// create path and map variables
@@ -175,12 +175,12 @@ class UserApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -197,7 +197,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -207,11 +207,11 @@ class UserApi {
///
///
Future<User> getUserByName(String username) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(username == null) {
throw new ApiException(400, "Missing required param: username");
throw ApiException(400, "Missing required param: username");
}
// create path and map variables
@@ -224,12 +224,12 @@ class UserApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = [];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -246,7 +246,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User;
} else {
@@ -257,14 +257,14 @@ class UserApi {
///
///
Future<String> loginUser(String username, String password) async {
Object postBody = null;
Object postBody;
// verify required params are set
if(username == null) {
throw new ApiException(400, "Missing required param: username");
throw ApiException(400, "Missing required param: username");
}
if(password == null) {
throw new ApiException(400, "Missing required param: password");
throw ApiException(400, "Missing required param: password");
}
// create path and map variables
@@ -279,12 +279,12 @@ class UserApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = [];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -301,7 +301,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String;
} else {
@@ -312,7 +312,7 @@ class UserApi {
///
///
Future logoutUser() async {
Object postBody = null;
Object postBody;
// verify required params are set
@@ -326,12 +326,12 @@ class UserApi {
List<String> contentTypes = [];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -348,7 +348,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;
@@ -357,15 +357,15 @@ class UserApi {
/// Updated user
///
/// This can only be done by the logged in user.
Future updateUser(String username, User body) async {
Object postBody = body;
Future updateUser(String username, User user) async {
Object postBody = user;
// verify required params are set
if(username == null) {
throw new ApiException(400, "Missing required param: username");
throw ApiException(400, "Missing required param: username");
}
if(body == null) {
throw new ApiException(400, "Missing required param: body");
if(user == null) {
throw ApiException(400, "Missing required param: user");
}
// create path and map variables
@@ -376,14 +376,14 @@ class UserApi {
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
List<String> contentTypes = [];
List<String> contentTypes = ["application/json"];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [];
String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json";
List<String> authNames = ["auth_cookie"];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
MultipartRequest mp = MultipartRequest(null, null);
if(hasFields)
postBody = mp;
}
@@ -400,7 +400,7 @@ class UserApi {
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
throw ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
} else {
return;

View File

@@ -10,18 +10,19 @@ class QueryParam {
class ApiClient {
String basePath;
var client = new Client();
var client = Client();
Map<String, String> _defaultHeaderMap = {};
Map<String, Authentication> _authentications = {};
final _RegList = new RegExp(r'^List<(.*)>$');
final _RegMap = new RegExp(r'^Map<String,(.*)>$');
final _regList = RegExp(r'^List<(.*)>$');
final _regMap = RegExp(r'^Map<String,(.*)>$');
ApiClient({this.basePath: "http://petstore.swagger.io/v2"}) {
ApiClient({this.basePath = "http://petstore.swagger.io/v2"}) {
// Setup authentications (key: authentication name, value: authentication).
_authentications['api_key'] = new ApiKeyAuth("header", "api_key");
_authentications['petstore_auth'] = new OAuth();
_authentications['api_key'] = ApiKeyAuth("header", "api_key");
_authentications['auth_cookie'] = ApiKeyAuth("query", "AUTH_KEY");
_authentications['petstore_auth'] = OAuth();
}
void addDefaultHeader(String key, String value) {
@@ -40,36 +41,40 @@ class ApiClient {
case 'double':
return value is double ? value : double.parse('$value');
case 'ApiResponse':
return new ApiResponse.fromJson(value);
return ApiResponse.fromJson(value);
case 'Category':
return new Category.fromJson(value);
return Category.fromJson(value);
case 'InlineObject':
return InlineObject.fromJson(value);
case 'InlineObject1':
return InlineObject1.fromJson(value);
case 'Order':
return new Order.fromJson(value);
return Order.fromJson(value);
case 'Pet':
return new Pet.fromJson(value);
return Pet.fromJson(value);
case 'Tag':
return new Tag.fromJson(value);
return Tag.fromJson(value);
case 'User':
return new User.fromJson(value);
return User.fromJson(value);
default:
{
Match match;
if (value is List &&
(match = _RegList.firstMatch(targetType)) != null) {
(match = _regList.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return value.map((v) => _deserialize(v, newTargetType)).toList();
} else if (value is Map &&
(match = _RegMap.firstMatch(targetType)) != null) {
(match = _regMap.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return new Map.fromIterables(value.keys,
return Map.fromIterables(value.keys,
value.values.map((v) => _deserialize(v, newTargetType)));
}
}
}
} catch (e, stack) {
throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack);
} on Exception catch (e, stack) {
throw ApiException.withInner(500, 'Exception during deserialization.', e, stack);
}
throw new ApiException(500, 'Could not find a suitable class for deserialization');
throw ApiException(500, 'Could not find a suitable class for deserialization');
}
dynamic deserialize(String json, String targetType) {
@@ -78,7 +83,7 @@ class ApiClient {
if (targetType == 'String') return json;
var decodedJson = JSON.decode(json);
var decodedJson = jsonDecode(json);
return _deserialize(decodedJson, targetType);
}
@@ -87,7 +92,7 @@ class ApiClient {
if (obj == null) {
serialized = '';
} else {
serialized = JSON.encode(obj);
serialized = json.encode(obj);
}
return serialized;
}
@@ -119,7 +124,7 @@ class ApiClient {
headerParams['Content-Type'] = contentType;
if(body is MultipartRequest) {
var request = new MultipartRequest(method, Uri.parse(url));
var request = MultipartRequest(method, Uri.parse(url));
request.fields.addAll(body.fields);
request.files.addAll(body.files);
request.headers.addAll(body.headers);
@@ -148,16 +153,14 @@ class ApiClient {
void _updateParamsForAuth(List<String> authNames, List<QueryParam> queryParams, Map<String, String> headerParams) {
authNames.forEach((authName) {
Authentication auth = _authentications[authName];
if (auth == null) throw new ArgumentError("Authentication undefined: " + authName);
if (auth == null) throw ArgumentError("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
});
}
void setAccessToken(String accessToken) {
_authentications.forEach((key, auth) {
if (auth is OAuth) {
auth.setAccessToken(accessToken);
}
});
T getAuthentication<T extends Authentication>(String name) {
var authentication = _authentications[name];
return authentication is T ? authentication : null;
}
}

View File

@@ -2,9 +2,9 @@ part of openapi.api;
class ApiException implements Exception {
int code = 0;
String message = null;
Exception innerException = null;
StackTrace stackTrace = null;
String message;
Exception innerException;
StackTrace stackTrace;
ApiException(this.code, this.message);
@@ -17,7 +17,7 @@ class ApiException implements Exception {
return "ApiException $code: $message";
}
return "ApiException $code: $message (Inner exception: ${innerException})\n\n" +
return "ApiException $code: $message (Inner exception: $innerException)\n\n" +
stackTrace.toString();
}
}

View File

@@ -11,7 +11,7 @@ Iterable<QueryParam> _convertParametersForCollectionFormat(
if (name == null || name.isEmpty || value == null) return params;
if (value is! List) {
params.add(new QueryParam(name, parameterToString(value)));
params.add(QueryParam(name, parameterToString(value)));
return params;
}
@@ -23,12 +23,12 @@ Iterable<QueryParam> _convertParametersForCollectionFormat(
: collectionFormat; // default: csv
if (collectionFormat == "multi") {
return values.map((v) => new QueryParam(name, parameterToString(v)));
return values.map((v) => QueryParam(name, parameterToString(v)));
}
String delimiter = _delimiters[collectionFormat] ?? ",";
params.add(new QueryParam(name, values.map((v) => parameterToString(v)).join(delimiter)));
params.add(QueryParam(name, values.map((v) => parameterToString(v)).join(delimiter)));
return params;
}

View File

@@ -4,22 +4,24 @@ class ApiKeyAuth implements Authentication {
final String location;
final String paramName;
String apiKey;
String _apiKey;
String apiKeyPrefix;
set apiKey(String key) => _apiKey = key;
ApiKeyAuth(this.location, this.paramName);
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
String value;
if (apiKeyPrefix != null) {
value = '$apiKeyPrefix $apiKey';
value = '$apiKeyPrefix $_apiKey';
} else {
value = apiKey;
value = _apiKey;
}
if (location == 'query' && value != null) {
queryParams.add(new QueryParam(paramName, value));
queryParams.add(QueryParam(paramName, value));
} else if (location == 'header' && value != null) {
headerParams[paramName] = value;
}

View File

@@ -2,13 +2,15 @@ part of openapi.api;
class HttpBasicAuth implements Authentication {
String username;
String password;
String _username;
String _password;
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str));
String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password);
headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str));
}
}
set username(String username) => _username = username;
set password(String password) => _password = password;
}

View File

@@ -1,19 +1,16 @@
part of openapi.api;
class OAuth implements Authentication {
String accessToken;
String _accessToken;
OAuth({this.accessToken}) {
}
OAuth({String accessToken}) : _accessToken = accessToken;
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
if (accessToken != null) {
headerParams["Authorization"] = "Bearer " + accessToken;
if (_accessToken != null) {
headerParams["Authorization"] = "Bearer $_accessToken";
}
}
void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
set accessToken(String accessToken) => _accessToken = accessToken;
}

View File

@@ -19,36 +19,39 @@ class ApiResponse {
if (json['code'] == null) {
code = null;
} else {
code = json['code'];
code = json['code'];
}
if (json['type'] == null) {
type = null;
} else {
type = json['type'];
type = json['type'];
}
if (json['message'] == null) {
message = null;
} else {
message = json['message'];
message = json['message'];
}
}
Map<String, dynamic> toJson() {
return {
'code': code,
'type': type,
'message': message
};
Map <String, dynamic> json = {};
if (code != null)
json['code'] = code;
if (type != null)
json['type'] = type;
if (message != null)
json['message'] = message;
return json;
}
static List<ApiResponse> listFromJson(List<dynamic> json) {
return json == null ? new List<ApiResponse>() : json.map((value) => new ApiResponse.fromJson(value)).toList();
return json == null ? List<ApiResponse>() : json.map((value) => ApiResponse.fromJson(value)).toList();
}
static Map<String, ApiResponse> mapFromJson(Map<String, Map<String, dynamic>> json) {
var map = new Map<String, ApiResponse>();
if (json != null && json.length > 0) {
json.forEach((String key, Map<String, dynamic> value) => map[key] = new ApiResponse.fromJson(value));
static Map<String, ApiResponse> mapFromJson(Map<String, dynamic> json) {
var map = Map<String, ApiResponse>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) => map[key] = ApiResponse.fromJson(value));
}
return map;
}

View File

@@ -17,30 +17,32 @@ class Category {
if (json['id'] == null) {
id = null;
} else {
id = json['id'];
id = json['id'];
}
if (json['name'] == null) {
name = null;
} else {
name = json['name'];
name = json['name'];
}
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name
};
Map <String, dynamic> json = {};
if (id != null)
json['id'] = id;
if (name != null)
json['name'] = name;
return json;
}
static List<Category> listFromJson(List<dynamic> json) {
return json == null ? new List<Category>() : json.map((value) => new Category.fromJson(value)).toList();
return json == null ? List<Category>() : json.map((value) => Category.fromJson(value)).toList();
}
static Map<String, Category> mapFromJson(Map<String, Map<String, dynamic>> json) {
var map = new Map<String, Category>();
if (json != null && json.length > 0) {
json.forEach((String key, Map<String, dynamic> value) => map[key] = new Category.fromJson(value));
static Map<String, Category> mapFromJson(Map<String, dynamic> json) {
var map = Map<String, Category>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) => map[key] = Category.fromJson(value));
}
return map;
}

View File

@@ -26,17 +26,17 @@ class Order {
if (json['id'] == null) {
id = null;
} else {
id = json['id'];
id = json['id'];
}
if (json['petId'] == null) {
petId = null;
} else {
petId = json['petId'];
petId = json['petId'];
}
if (json['quantity'] == null) {
quantity = null;
} else {
quantity = json['quantity'];
quantity = json['quantity'];
}
if (json['shipDate'] == null) {
shipDate = null;
@@ -46,34 +46,40 @@ class Order {
if (json['status'] == null) {
status = null;
} else {
status = json['status'];
status = json['status'];
}
if (json['complete'] == null) {
complete = null;
} else {
complete = json['complete'];
complete = json['complete'];
}
}
Map<String, dynamic> toJson() {
return {
'id': id,
'petId': petId,
'quantity': quantity,
'shipDate': shipDate == null ? '' : shipDate.toUtc().toIso8601String(),
'status': status,
'complete': complete
};
Map <String, dynamic> json = {};
if (id != null)
json['id'] = id;
if (petId != null)
json['petId'] = petId;
if (quantity != null)
json['quantity'] = quantity;
if (shipDate != null)
json['shipDate'] = shipDate == null ? null : shipDate.toUtc().toIso8601String();
if (status != null)
json['status'] = status;
if (complete != null)
json['complete'] = complete;
return json;
}
static List<Order> listFromJson(List<dynamic> json) {
return json == null ? new List<Order>() : json.map((value) => new Order.fromJson(value)).toList();
return json == null ? List<Order>() : json.map((value) => Order.fromJson(value)).toList();
}
static Map<String, Order> mapFromJson(Map<String, Map<String, dynamic>> json) {
var map = new Map<String, Order>();
if (json != null && json.length > 0) {
json.forEach((String key, Map<String, dynamic> value) => map[key] = new Order.fromJson(value));
static Map<String, Order> mapFromJson(Map<String, dynamic> json) {
var map = Map<String, Order>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) => map[key] = Order.fromJson(value));
}
return map;
}

View File

@@ -26,22 +26,22 @@ class Pet {
if (json['id'] == null) {
id = null;
} else {
id = json['id'];
id = json['id'];
}
if (json['category'] == null) {
category = null;
} else {
category = new Category.fromJson(json['category']);
category = Category.fromJson(json['category']);
}
if (json['name'] == null) {
name = null;
} else {
name = json['name'];
name = json['name'];
}
if (json['photoUrls'] == null) {
photoUrls = null;
} else {
photoUrls = (json['photoUrls'] as List).map((item) => item as String).toList();
photoUrls = (json['photoUrls'] as List).cast<String>();
}
if (json['tags'] == null) {
tags = null;
@@ -51,29 +51,35 @@ class Pet {
if (json['status'] == null) {
status = null;
} else {
status = json['status'];
status = json['status'];
}
}
Map<String, dynamic> toJson() {
return {
'id': id,
'category': category,
'name': name,
'photoUrls': photoUrls,
'tags': tags,
'status': status
};
Map <String, dynamic> json = {};
if (id != null)
json['id'] = id;
if (category != null)
json['category'] = category;
if (name != null)
json['name'] = name;
if (photoUrls != null)
json['photoUrls'] = photoUrls;
if (tags != null)
json['tags'] = tags;
if (status != null)
json['status'] = status;
return json;
}
static List<Pet> listFromJson(List<dynamic> json) {
return json == null ? new List<Pet>() : json.map((value) => new Pet.fromJson(value)).toList();
return json == null ? List<Pet>() : json.map((value) => Pet.fromJson(value)).toList();
}
static Map<String, Pet> mapFromJson(Map<String, Map<String, dynamic>> json) {
var map = new Map<String, Pet>();
if (json != null && json.length > 0) {
json.forEach((String key, Map<String, dynamic> value) => map[key] = new Pet.fromJson(value));
static Map<String, Pet> mapFromJson(Map<String, dynamic> json) {
var map = Map<String, Pet>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) => map[key] = Pet.fromJson(value));
}
return map;
}

Some files were not shown because too many files have changed in this diff Show More