Merge remote-tracking branch 'origin/master' into 2.3.0

This commit is contained in:
wing328 2016-10-16 16:04:17 +08:00
commit 6ac9f0f351
642 changed files with 71183 additions and 1446 deletions

View File

@ -873,6 +873,7 @@ Here is a list of template creators:
* Javascript (Closure-annotated Angular) @achew22
* Perl: @wing328
* Swift: @tkqubo
* Swift 3: @hexelon
* TypeScript (Node): @mhardorf
* TypeScript (Angular1): @mhardorf
* TypeScript (Fetch): @leonyu

40
bin/swift3-petstore-all.sh Executable file
View File

@ -0,0 +1,40 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore.json -o samples/client/petstore/swift3/default"
echo "#### Petstore Swift API client (default) ####"
java $JAVA_OPTS -jar $executable $ags
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-promisekit.json -o samples/client/petstore/swift3/promisekit"
echo "#### Petstore Swift API client (promisekit) ####"
java $JAVA_OPTS -jar $executable $ags
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-rxswift.json -o samples/client/petstore/swift3/rxswift"
echo "#### Petstore Swift API client (rxswift) ####"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,7 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "PromiseKit"
}

View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-promisekit.json -o samples/client/petstore/swift/promisekit"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,7 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "RxSwift"
}

31
bin/swift3-petstore-rxswift.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-rxswift.json -o samples/client/petstore/swift3/rxswift"
java $JAVA_OPTS -jar $executable $ags

6
bin/swift3-petstore.json Normal file
View File

@ -0,0 +1,6 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
"podAuthors": "",
"projectName": "PetstoreClient"
}

31
bin/swift3-petstore.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore.json -o samples/client/petstore/swift3/default"
java $JAVA_OPTS -jar $executable $ags

View File

@ -9,7 +9,7 @@ public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
public String example; // example value (x-example)
public String jsonSchema;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
@ -85,6 +85,7 @@ public class CodegenParameter {
output.paramName = this.paramName;
output.dataType = this.dataType;
output.datatypeWithEnum = this.datatypeWithEnum;
output.enumName = this.enumName;
output.dataFormat = this.dataFormat;
output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
@ -182,6 +183,8 @@ public class CodegenParameter {
return false;
if (datatypeWithEnum != null ? !datatypeWithEnum.equals(that.datatypeWithEnum) : that.datatypeWithEnum != null)
return false;
if (enumName != null ? !enumName.equals(that.enumName) : that.enumName != null)
return false;
if (dataFormat != null ? !dataFormat.equals(that.dataFormat) : that.dataFormat != null)
return false;
if (collectionFormat != null ? !collectionFormat.equals(that.collectionFormat) : that.collectionFormat != null)
@ -279,6 +282,7 @@ public class CodegenParameter {
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (datatypeWithEnum != null ? datatypeWithEnum.hashCode() : 0);
result = 31 * result + (enumName != null ? enumName.hashCode() : 0);
result = 31 * result + (dataFormat != null ? dataFormat.hashCode() : 0);
result = 31 * result + (collectionFormat != null ? collectionFormat.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);

View File

@ -1307,13 +1307,15 @@ public class DefaultCodegen {
addVars(m, properties, required, allProperties, allRequired);
} else {
ModelImpl impl = (ModelImpl) model;
if (m != null && impl.getType() != null) {
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p);
}
if(impl.getEnum() != null && impl.getEnum().size() > 0) {
m.isEnum = true;
// comment out below as allowableValues is not set in post processing model enum
m.allowableValues = new HashMap<String, Object>();
m.allowableValues.put("values", impl.getEnum());
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p);
}
if (impl.getAdditionalProperties() != null) {
addAdditionPropertiesToCodeGenModel(m, impl);
@ -2263,6 +2265,7 @@ public class DefaultCodegen {
p.dataFormat = cp.dataFormat;
if(cp.isEnum) {
p.datatypeWithEnum = cp.datatypeWithEnum;
p.enumName = cp.enumName;
}
// enum
@ -2274,6 +2277,7 @@ public class DefaultCodegen {
if (cp.items != null && cp.items.isEnum) {
p.datatypeWithEnum = cp.datatypeWithEnum;
p.enumName = cp.enumName;
p.items = cp.items;
}
p.collectionFormat = collectionFormat;

View File

@ -15,6 +15,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
public static final String USE_RX_JAVA = "useRxJava";
public static final String PARCELABLE_MODEL = "parcelableModel";
public static final String SUPPORT_JAVA6 = "supportJava6";
public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";
@ -22,6 +23,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean parcelableModel = false;
protected boolean supportJava6= false;
public JavaClientCodegen() {
super();
@ -34,8 +36,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library. (Default: false)"));
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'.");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'");
@ -44,9 +47,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
// set okhttp-gson as the default
libraryOption.setDefault("okhttp-gson");
cliOptions.add(libraryOption);
setLibrary("okhttp-gson");
}
@ -79,6 +82,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
// put the boolean value back to PARCELABLE_MODEL in additionalProperties
additionalProperties.put(PARCELABLE_MODEL, parcelableModel);
if (additionalProperties.containsKey(SUPPORT_JAVA6)) {
this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString()));
}
additionalProperties.put(SUPPORT_JAVA6, supportJava6);
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@ -97,11 +105,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java"));
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
@ -235,4 +243,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
public void setParcelableModel(boolean parcelableModel) {
this.parcelableModel = parcelableModel;
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}
}

View File

@ -336,6 +336,33 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
}
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// camelize (lower first character) the variable name
// petId => pet_id
name = underscore(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
return toVarName(name);
}
@Override
public String toApiName(String type) {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";

View File

@ -172,6 +172,7 @@ public class SpringCodegen extends AbstractJavaCodegen {
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");

View File

@ -0,0 +1,549 @@
package io.swagger.codegen.languages;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import javax.annotation.Nullable;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
public static final String RESPONSE_AS = "responseAs";
public static final String UNWRAP_REQUIRED = "unwrapRequired";
public static final String POD_SOURCE = "podSource";
public static final String POD_AUTHORS = "podAuthors";
public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL";
public static final String POD_DOCSET_URL = "podDocsetURL";
public static final String POD_LICENSE = "podLicense";
public static final String POD_HOMEPAGE = "podHomepage";
public static final String POD_SUMMARY = "podSummary";
public static final String POD_DESCRIPTION = "podDescription";
public static final String POD_SCREENSHOTS = "podScreenshots";
public static final String POD_DOCUMENTATION_URL = "podDocumentationURL";
public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen";
protected static final String LIBRARY_PROMISE_KIT = "PromiseKit";
protected static final String LIBRARY_RX_SWIFT = "RxSwift";
protected static final String[] RESPONSE_LIBRARIES = {LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT};
protected String projectName = "SwaggerClient";
protected boolean unwrapRequired;
protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "Swaggers";
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "swift3";
}
@Override
public String getHelp() {
return "Generates a swift client library.";
}
public Swift3Codegen() {
super();
outputFolder = "generated-code" + File.separator + "swift";
modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift");
embeddedTemplateDir = templateDir = "swift";
apiPackage = File.separator + "APIs";
modelPackage = File.separator + "Models";
languageSpecificPrimitives = new HashSet<>(
Arrays.asList(
"Int",
"Int32",
"Int64",
"Float",
"Double",
"Bool",
"Void",
"String",
"Character",
"AnyObject",
"Any")
);
defaultIncludes = new HashSet<>(
Arrays.asList(
"Data",
"Date",
"URL", // for file
"UUID",
"Array",
"Dictionary",
"Set",
"Any",
"Empty",
"AnyObject",
"Any")
);
reservedWords = new HashSet<>(
Arrays.asList(
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any",
"class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak")
);
typeMapping = new HashMap<>();
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "Date");
typeMapping.put("Date", "Date");
typeMapping.put("DateTime", "Date");
typeMapping.put("boolean", "Bool");
typeMapping.put("string", "String");
typeMapping.put("char", "Character");
typeMapping.put("short", "Int");
typeMapping.put("int", "Int32");
typeMapping.put("long", "Int64");
typeMapping.put("integer", "Int32");
typeMapping.put("Integer", "Int32");
typeMapping.put("float", "Float");
typeMapping.put("number", "Double");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "URL");
typeMapping.put("binary", "Data");
typeMapping.put("ByteArray", "Data");
typeMapping.put("UUID", "UUID");
importMapping = new HashMap<>();
cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode"));
cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " +
StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available."));
cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " +
"(which would crash the app if api returns null as opposed to required option specified in json schema"));
cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec"));
cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec"));
cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec"));
cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec"));
cliOptions.add(new CliOption(POD_DOCSET_URL, "Docset URL used for Podspec"));
cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec"));
cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec"));
cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec"));
cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec"));
cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec"));
cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec"));
cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API"));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated")
.defaultValue(Boolean.TRUE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
// default HIDE_GENERATION_TIMESTAMP to true
if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString());
} else {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString()));
}
// Setup project name
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName((String) additionalProperties.get(PROJECT_NAME));
} else {
additionalProperties.put(PROJECT_NAME, projectName);
}
sourceFolder = projectName + File.separator + sourceFolder;
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(RESPONSE_AS)) {
Object responseAsObject = additionalProperties.get(RESPONSE_AS);
if (responseAsObject instanceof String) {
setResponseAs(((String) responseAsObject).split(","));
} else {
setResponseAs((String[]) responseAsObject);
}
}
additionalProperties.put(RESPONSE_AS, responseAs);
if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) {
additionalProperties.put("usePromiseKit", true);
}
if (ArrayUtils.contains(responseAs, LIBRARY_RX_SWIFT)) {
additionalProperties.put("useRxSwift", true);
}
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
}
supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec"));
supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile"));
supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift"));
supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder,
"AlamofireImplementations.swift"));
supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift"));
supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift"));
supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}
@Override
protected boolean isReservedWord(String word) {
return word != null && reservedWords.contains(word); //don't lowercase as super does
}
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar);
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "[String:" + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type))
return type;
} else
type = swaggerType;
return toModelName(type);
}
@Override
public boolean isDataTypeBinary(final String dataType) {
return dataType != null && dataType.equals("Data");
}
/**
* Output the proper model name (capitalized)
*
* @param name the name of the model
* @return capitalized model name
*/
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final"
if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix
name = name + "_" + modelNameSuffix;
}
if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix
name = modelNamePrefix + "_" + name;
}
// camelize the model name
// phone_number => PhoneNumber
name = camelize(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = "Model" + name;
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return name;
}
/**
* Return the capitalized file name of the model
*
* @param name the model name
* @return the file name of the model
*/
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String toDefaultValue(Property p) {
// nil
return null;
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "[String:" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public String toApiName(String name) {
if (name.length() == 0)
return "DefaultAPI";
return initialCaps(name) + "API";
}
@Override
public String toOperationId(String operationId) {
operationId = camelize(sanitizeName(operationId), true);
// throw exception if method name is empty. This should not happen but keep the check just in case
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
String newOperationId = camelize(("call_" + operationId), true);
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId);
return newOperationId;
}
return operationId;
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// sanitize name
name = sanitizeName(name);
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize(lower) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions, swagger);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public void setUnwrapRequired(boolean unwrapRequired) {
this.unwrapRequired = unwrapRequired;
}
public void setResponseAs(String[] responseAs) {
this.responseAs = responseAs;
}
@Override
public String toEnumValue(String value, String datatype) {
return String.valueOf(value);
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true);
}
if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
String varName = "number" + camelize(name);
varName = varName.replaceAll("-", "minus");
varName = varName.replaceAll("\\+", "plus");
varName = varName.replaceAll("\\.", "dot");
return varName;
}
// Prevent from breaking properly cased identifier
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return camelize(name, true);
}
char[] separators = {'-', '_', ' ', ':', '(', ')'};
return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true);
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name);
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
if (isReservedWord(property.datatypeWithEnum) || toVarName(property.name).equals(property.datatypeWithEnum)) {
enumName = property.datatypeWithEnum + "Enum";
}
// TODO: toModelName already does something for names starting with number, so this code is probably never called
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -79,6 +79,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
{{/vars}}
{{^supportJava6}}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
@ -99,6 +100,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
{{/supportJava6}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

View File

@ -4,9 +4,9 @@ package {{package}};
{{/imports}}
import io.swagger.annotations.*;
{{#java8}}
{{#jdk8}}
import org.springframework.http.HttpStatus;
{{/java8}}
{{/jdk8}}
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@ -19,7 +19,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.List;
{{#async}}
import java.util.concurrent.{{^java8}}Callable{{/java8}}{{#java8}}CompletableFuture{{/java8}};
import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}};
{{/async}}
{{>generatedAnnotation}}
@ -43,10 +43,11 @@ public interface {{classname}} {
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
method = RequestMethod.{{httpMethod}})
{{#java8}}default {{/java8}}{{#async}}{{^java8}}Callable{{/java8}}{{#java8}}CompletableFuture<{{/java8}}{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}){{^java8}};{{/java8}}{{#java8}} {
{{#jdk8}}default {{/jdk8}}{{#async}}{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture<{{/jdk8}}{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} {
// do some magic!
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};
}{{/java8}}
}{{/jdk8}}
{{/operation}}
}

View File

@ -1,6 +1,6 @@
package {{package}};
{{^java8}}
{{^jdk8}}
{{#imports}}import {{import}};
{{/imports}}
@ -8,9 +8,9 @@ import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
{{/java8}}
{{/jdk8}}
import org.springframework.stereotype.Controller;
{{^java8}}
{{^jdk8}}
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@ -21,13 +21,13 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.List;
{{#async}}
import java.util.concurrent.Callable;
{{/async}}{{/java8}}
{{/async}}{{/jdk8}}
{{>generatedAnnotation}}
@Controller
{{#operations}}
public class {{classname}}Controller implements {{classname}} {
{{^java8}}{{#operation}}
{{^jdk8}}{{#operation}}
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) {
// do some magic!{{^async}}
@ -39,6 +39,6 @@ public class {{classname}}Controller implements {{classname}} {
}
};{{/async}}
}
{{/operation}}{{/java8}}
{{/operation}}{{/jdk8}}
}
{{/operations}}

View File

@ -41,6 +41,7 @@ io.swagger.codegen.languages.StaticHtml2Generator
io.swagger.codegen.languages.SwaggerGenerator
io.swagger.codegen.languages.SwaggerYamlGenerator
io.swagger.codegen.languages.SwiftCodegen
io.swagger.codegen.languages.Swift3Codegen
io.swagger.codegen.languages.TizenClientCodegen
io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen
io.swagger.codegen.languages.TypeScriptAngularClientCodegen

View File

@ -102,16 +102,16 @@ export const {{classname}}FetchParamCreactor = {
fetchOptions.body = JSON.stringify(params["{{paramName}}"] || {});
}{{/bodyParam}}
{{/hasBodyParam}}
{{#hasHeaderParam}}
{{#hasHeaderParams}}
fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}}
"{{baseName}}": params.{{paramName}},{{/headerParams}}
}, contentTypeHeader);
{{/hasHeaderParam}}
{{^hasHeaderParam}}
{{/hasHeaderParams}}
{{^hasHeaderParams}}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
{{/hasHeaderParam}}
{{/hasHeaderParams}}
return {
url: url.format(urlObj),
options: fetchOptions,

View File

@ -24,7 +24,7 @@ void
fullPath.append(this->host).append(this->basePath).append("{{path}}");
{{#pathParams}}
QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}");
QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{baseName}}").append("}");
fullPath.replace({{paramName}}PathParam, stringValue({{paramName}}));
{{/pathParams}}
@ -34,7 +34,7 @@ void
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("{{paramName}}"))
fullPath.append(QUrl::toPercentEncoding("{{baseName}}"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue({{paramName}})));
{{/collectionFormat}}
@ -48,7 +48,7 @@ void
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{{paramName}}}=").append(stringValue(t));
fullPath.append("{{{baseName}}}=").append(stringValue(t));
}
}
else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) {
@ -56,7 +56,7 @@ void
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{paramName}}=");
fullPath.append("{{baseName}}=");
qint32 count = 0;
foreach({{{baseType}}} t, *{{paramName}}) {
if (count > 0) {
@ -70,7 +70,7 @@ void
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{paramName}}=");
fullPath.append("{{baseName}}=");
qint32 count = 0;
foreach({{{baseType}}} t, *{{paramName}}) {
if (count > 0) {
@ -88,7 +88,7 @@ void
HttpRequestInput input(fullPath, "{{httpMethod}}");
{{#formParams}}if ({{paramName}} != NULL) {
{{^isFile}}input.add_var("{{paramName}}", *{{paramName}});{{/isFile}}{{#isFile}}input.add_file("{{paramName}}", (*{{paramName}}).local_filename, (*{{paramName}}).request_filename, (*{{paramName}}).mime_type);{{/isFile}}
{{^isFile}}input.add_var("{{baseName}}", *{{paramName}});{{/isFile}}{{#isFile}}input.add_file("{{baseName}}", (*{{paramName}}).local_filename, (*{{paramName}}).request_filename, (*{{paramName}}).mime_type);{{/isFile}}
}
{{/formParams}}

View File

@ -0,0 +1,42 @@
// APIHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
class APIHelper {
static func rejectNil(_ source: [String:Any?]) -> [String:Any]? {
var destination = [String:Any]()
for (key, nillableValue) in source {
if let value: Any = nillableValue {
destination[key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? {
guard let source = source else {
return nil
}
var destination = [String:Any]()
let theTrue = NSNumber(value: true as Bool)
let theFalse = NSNumber(value: false as Bool)
for (key, value) in source {
switch value {
case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse:
destination[key] = "\(value as! Bool)" as Any?
default:
destination[key] = value
}
}
return destination
}
}

View File

@ -0,0 +1,76 @@
// APIs.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class {{projectName}}API {
open static var basePath = "{{basePath}}"
open static var credential: URLCredential?
open static var customHeaders: [String:String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
open class APIBase {
func toParameters(_ encodable: JSONEncodable?) -> [String: Any]? {
let encoded: Any? = encodable?.encodeToJSON()
if encoded! is [Any] {
var dictionary = [String:Any]()
for (index, item) in (encoded as! [Any]).enumerated() {
dictionary["\(index)"] = item
}
return dictionary
} else {
return encoded as? [String:Any]
}
}
}
open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String:String] = [:]
let parameters: [String:Any]?
let isBody: Bool
let method: String
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((Progress) -> ())?
required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
addHeaders({{projectName}}API.customHeaders)
}
open func addHeaders(_ aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) { }
public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
open func addCredential() -> Self {
self.credential = {{projectName}}API.credential
return self
}
}
public protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -0,0 +1,191 @@
// AlamofireImplementations.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
}
// Store manager to retain its reference
private var managerStore: [String: Alamofire.SessionManager] = [:]
open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody)
}
/**
May be overridden by a subclass if you want to control the session
configuration.
*/
open func createSessionManager() -> Alamofire.SessionManager {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = buildHeaders()
return Alamofire.SessionManager(configuration: configuration)
}
override open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
let managerId:String = UUID().uuidString
// Create a new manager for each request to customize its request header
let manager = createSessionManager()
managerStore[managerId] = manager
let encoding:ParameterEncoding = isBody ? JSONEncoding() : URLEncoding()
let xMethod = Alamofire.HTTPMethod(rawValue: method)
let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(multipartFormData: { mpForm in
for (k, v) in self.parameters! {
switch v {
case let fileURL as URL:
mpForm.append(fileURL, withName: k)
break
case let string as String:
mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k)
break
case let number as NSNumber:
mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k)
break
default:
fatalError("Unprocessable value \(v) with key \(k)")
break
}
}
}, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
if let onProgressReady = self.onProgressReady {
onProgressReady(upload.progress)
}
self.processRequest(request: upload, managerId, completion)
case .failure(let encodingError):
completion(nil, ErrorResponse.Error(415, nil, encodingError))
}
})
} else {
let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request: request, managerId, completion)
}
}
private func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
_ = managerStore.removeValue(forKey: managerId)
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
Response(
response: stringResponse.response!,
body: ((stringResponse.result.value ?? "") as! T)
),
nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
nil,
ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
Response(
response: voidResponse.response!,
body: nil),
nil
)
})
case is Data.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if (dataResponse.result.isFailure) {
completion(
nil,
ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
Response(
response: dataResponse.response!,
body: (dataResponse.data as! T)
),
nil
)
})
default:
validatedRequest.responseJSON(options: .allowFragments) { response in
cleanupRequest()
if response.result.isFailure {
completion(nil, ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!))
return
}
if () is T {
completion(Response(response: response.response!, body: (() as! T)), nil)
return
}
if let json: Any = response.result.value {
let body = Decoders.decode(clazz: T.self, source: json as AnyObject)
completion(Response(response: response.response!, body: body), nil)
return
} else if "" is T {
// swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release
// https://github.com/swagger-api/swagger-parser/pull/34
completion(Response(response: response.response!, body: ("" as! T)), nil)
return
}
completion(nil, ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
}
}
}
private func buildHeaders() -> [String: String] {
var httpHeaders = SessionManager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
}

View File

@ -0,0 +1,3 @@
github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}}
github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}{{#useRxSwift}}
github "ReactiveX/RxSwift" ~> 2.0{{/useRxSwift}}

View File

@ -0,0 +1,99 @@
// Extensions.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}
extension Bool: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Float: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int32) }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int64) }
}
extension Double: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension String: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
private func encodeIfPossible<T>(_ object: T) -> Any {
if let encodableObject = object as? JSONEncodable {
return encodableObject.encodeToJSON()
} else {
return object as Any
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> Any {
return self.map(encodeIfPossible)
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> Any {
var dictionary = [AnyHashable: Any]()
for (key, value) in self {
dictionary[key as! NSObject] = encodeIfPossible(value)
}
return dictionary as Any
}
}
extension Data: JSONEncodable {
func encodeToJSON() -> Any {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
private let dateFormatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
fmt.locale = Locale(identifier: "en_US_POSIX")
return fmt
}()
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return dateFormatter.string(from: self) as Any
}
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any {
return self.uuidString
}
}
{{#usePromiseKit}}extension RequestBuilder {
public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pending()
self.execute { (response: Response<T>?, error: Error?) in
if let response = response {
deferred.fulfill(response)
} else {
deferred.reject(error!)
}
}
return deferred.promise
}
}{{/usePromiseKit}}

View File

@ -0,0 +1,199 @@
// Models.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> Any
}
public enum ErrorResponse : Error {
case Error(Int, Data?, Error)
}
open class Response<T> {
open let statusCode: Int
open let header: [String: String]
open let body: T?
public init(statusCode: Int, header: [String: String], body: T?) {
self.statusCode = statusCode
self.header = header
self.body = body
}
public convenience init(response: HTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String:String]()
for (key, value) in rawHeader {
header[key as! String] = value as? String
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
private var once = Int()
class Decoders {
static fileprivate var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static func addDecoder<T>(clazz: T.Type, decoder: @escaping ((AnyObject) -> T)) {
let key = "\(T.self)"
decoders[key] = { decoder($0) as AnyObject }
}
static func decode<T>(clazz: [T].Type, source: AnyObject) -> [T] {
let array = source as! [AnyObject]
return array.map { Decoders.decode(clazz: T.self, source: $0) }
}
static func decode<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject) -> [Key:T] {
let sourceDictionary = source as! [Key: AnyObject]
var dictionary = [Key:T]()
for (key, value) in sourceDictionary {
dictionary[key] = Decoders.decode(clazz: T.self, source: value)
}
return dictionary
}
static func decode<T>(clazz: T.Type, source: AnyObject) -> T {
initialize()
if T.self is Int32.Type && source is NSNumber {
return source.int32Value as! T;
}
if T.self is Int64.Type && source is NSNumber {
return source.int64Value as! T;
}
if T.self is UUID.Type && source is String {
return UUID(uuidString: source as! String) as! T
}
if source is T {
return source as! T
}
if T.self is Data.Type && source is String {
return Data(base64Encoded: source as! String) as! T
}
let key = "\(T.self)"
if let decoder = decoders[key] {
return decoder(source) as! T
} else {
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
}
}
static func decodeOptional<T>(clazz: T.Type, source: AnyObject?) -> T? {
if source is NSNull {
return nil
}
return source.map { (source: AnyObject) -> T in
Decoders.decode(clazz: clazz, source: source)
}
}
static func decodeOptional<T>(clazz: [T].Type, source: AnyObject?) -> [T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
static func decodeOptional<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [Key:T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
private static var __once: () = {
let formatters = [
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS"
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}
// Decoder for Date
Decoders.addDecoder(clazz: Date.self) { (source: AnyObject) -> Date in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.date(from: sourceString) {
return date
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return Date(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
} {{#models}}{{#model}}
// Decoder for [{{{classname}}}]
Decoders.addDecoder(clazz: [{{{classname}}}].self) { (source: AnyObject) -> [{{{classname}}}] in
return Decoders.decode(clazz: [{{{classname}}}].self, source: source)
}
// Decoder for {{{classname}}}
Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in
{{#isArrayModel}}
let sourceArray = source as! [AnyObject]
return sourceArray.map({ Decoders.decode(clazz: {{{arrayModelType}}}.self, source: $0) })
{{/isArrayModel}}
{{^isArrayModel}}
{{#isEnum}}
if let source = source as? {{dataType}} {
if let result = {{classname}}(rawValue: source) {
return result
}
}
fatalError("Source \(source) is not convertible to enum type {{classname}}: Maybe swagger file is insufficient")
{{/isEnum}}
{{^isEnum}}
{{#vars.isEmpty}}
if let source = source as? {{dataType}} {
return source
}
fatalError("Source \(source) is not convertible to typealias {{classname}}: Maybe swagger file is insufficient")
{{/vars.isEmpty}}
{{^vars.isEmpty}}
let sourceDictionary = source as! [AnyHashable: Any]
{{#unwrapRequired}}
let instance = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{#isEnum}}{{name}}: {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as! {{datatype}}))! {{/isEnum}}{{^isEnum}}{{name}}: Decoders.decode(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]! as AnyObject){{/isEnum}}{{/requiredVars}})
{{#optionalVars}}{{#isEnum}}
if let {{name}} = sourceDictionary["{{baseName}}"] as? {{datatype}} { {{^isContainer}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: ({{name}})){{/isContainer}}{{#isListContainer}}
instance.{{name}} = {{name}}.map ({ {{classname}}.{{enumName}}(rawValue: $0)! }){{/isListContainer}}
}{{/isEnum}}{{^isEnum}}
instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}
{{/optionalVars}}
{{/unwrapRequired}}
{{^unwrapRequired}}
let instance = {{classname}}(){{#vars}}{{#isEnum}}
if let {{name}} = sourceDictionary["{{baseName}}"] as? {{datatype}} { {{^isContainer}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: ({{name}})){{/isContainer}}{{#isListContainer}}
instance.{{name}} = {{name}}.map ({ {{classname}}.{{enumName}}(rawValue: $0)! }){{/isListContainer}}{{#isMapContainer}}//TODO: handle enum map scenario{{/isMapContainer}}
}{{/isEnum}}
{{^isEnum}}instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}{{/vars}}
{{/unwrapRequired}}
return instance
{{/vars.isEmpty}}
{{/isEnum}}
{{/isArrayModel}}
}{{/model}}
{{/models}}
}()
static fileprivate func initialize() {
_ = Decoders.__once
}
}

View File

@ -0,0 +1,21 @@
Pod::Spec.new do |s|
s.name = '{{projectName}}'{{#projectDescription}}
s.summary = '{{projectDescription}}'{{/projectDescription}}
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}'
s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}}
s.authors = '{{podAuthors}}'{{/podAuthors}}{{#podSocialMediaURL}}
s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}}
s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}}
s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}}
s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}}
s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}}
s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}}
s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}}
s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}}
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}}
s.dependency 'PromiseKit', '~> 4.0'{{/usePromiseKit}}{{#useRxSwift}}
s.dependency 'RxSwift', '~> 3.0.0-beta.1'{{/useRxSwift}}
s.dependency 'Alamofire', '~> 4.0'
end

View File

@ -0,0 +1 @@
"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#isDate}}{{^required}}?{{/required}}.encodeToJSON(){{/isDate}}{{#isDateTime}}{{^required}}?{{/required}}.encodeToJSON(){{/isDateTime}}

View File

@ -0,0 +1,132 @@
{{#operations}}//
// {{classname}}.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
import RxSwift{{/useRxSwift}}
{{#swiftUseApiNamespace}}
extension {{projectName}}API {
{{/swiftUseApiNamespace}}
{{#description}}
/** {{description}} */{{/description}}
open class {{classname}}: APIBase {
{{#operation}}
{{#allParams}}
{{#isEnum}}
/**
* enum for parameter {{paramName}}
*/
public enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}}
case {{name}} = {{#isContainer}}"{{/isContainer}}{{#isString}}"{{/isString}}{{{value}}}{{#isString}}"{{/isString}}{{#isContainer}}"{{/isContainer}}{{/enumVars}}{{/allowableValues}}
}
{{/isEnum}}
{{/allParams}}
/**
{{#summary}}
{{{summary}}}
{{/summary}}{{#allParams}}
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- parameter completion: completion handler to receive the data and the error objects
*/
open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping ((_ {{#returnType}}data: {{{returnType}}}?,_ {{/returnType}}error: Error?) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in
completion({{#returnType}}response?.body, {{/returnType}}error);
}
}
{{#usePromiseKit}}
/**
{{#summary}}
{{{summary}}}
{{/summary}}{{#allParams}}
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- returns: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
*/
open class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending()
{{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in
if let error = error {
deferred.reject(error)
} else {
deferred.fulfill({{#returnType}}data!{{/returnType}})
}
}
return deferred.promise
}
{{/usePromiseKit}}
{{#useRxSwift}}
/**
{{#summary}}
{{{summary}}}
{{/summary}}{{#allParams}}
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- returns: Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
*/
open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
return Observable.create { observer -> Disposable in
{{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in
if let error = error {
observer.on(.error(error as Error))
} else {
observer.on(.next({{#returnType}}data!{{/returnType}}))
}
observer.on(.completed)
}
return NopDisposable.instance
}
}
{{/useRxSwift}}
/**
{{#summary}}
{{{summary}}}
{{/summary}}
- {{httpMethod}} {{path}}{{#notes}}
- {{{notes}}}{{/notes}}{{#subresourceOperation}}
- subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}}
- defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}}
- {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}:
- type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}}
- name: {{name}}{{/authMethods}}{{#responseHeaders}}
- responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}}
- examples: {{{examples}}}{{/examples}}{{#externalDocs}}
- externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}}
{{/hasParams}}{{#allParams}}
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}}
*/
open class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
{{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}}
path = path.replacingOccurrences(of: "{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", with: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .literal, range: nil){{/pathParams}}
let URLString = {{projectName}}API.basePath + path
{{#bodyParam}}
let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}}
let nillableParameters: [String:Any?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}}
{{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}}
{{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/queryParams}}
let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}}
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}})
}
{{/operation}}
}
{{#swiftUseApiNamespace}}
}
{{/swiftUseApiNamespace}}
{{/operations}}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,63 @@
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
## Other
*.xccheckout
*.moved-aside
*.xcuserstate
*.xcscmblueprint
## Obj-C/Swift specific
*.hmap
*.ipa
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
.build/
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
fastlane/report.xml
fastlane/screenshots

View File

@ -0,0 +1,77 @@
{{#models}}{{#model}}//
// {{classname}}.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
{{#description}}
/** {{description}} */{{/description}}
{{#isArrayModel}}
public typealias {{classname}} = [{{arrayModelType}}]
{{/isArrayModel}}
{{^isArrayModel}}
{{#isEnum}}
public enum {{classname}}: {{dataType}} {
{{#allowableValues}}{{#enumVars}} case {{name}} = "{{{value}}}"
{{/enumVars}}{{/allowableValues}}
func encodeToJSON() -> Any { return self.rawValue }
}
{{/isEnum}}
{{^isEnum}}
{{#vars.isEmpty}}
public typealias {{classname}} = {{dataType}}
{{/vars.isEmpty}}
{{^vars.isEmpty}}
open class {{classname}}: JSONEncodable {
{{#vars}}
{{#isEnum}}
public enum {{enumName}}: {{^isContainer}}{{datatype}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}}
case {{name}} = {{#isContainer}}"{{/isContainer}}{{#isString}}"{{/isString}}{{{value}}}{{#isString}}"{{/isString}}{{#isContainer}}"{{/isContainer}}{{/enumVars}}{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
{{#vars}}
{{#isEnum}}
{{#description}}/** {{description}} */
{{/description}}public var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{/isEnum}}
{{^isEnum}}
{{#description}}/** {{description}} */
{{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{/isEnum}}
{{/vars}}
{{^unwrapRequired}}
public init() {}
{{/unwrapRequired}}
{{#unwrapRequired}}
public init({{#allVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{datatype}}{{/isEnum}}{{^required}}?=nil{{/required}}{{/allVars}}) {
{{#allVars}}
self.{{name}} = {{name}}
{{/allVars}}
}
{{/unwrapRequired}}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isInteger}}{{#isLong}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isLong}}{{^isLong}}{{^isInteger}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{/isInteger}}{{/isLong}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}}{{^isEnum}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isEnum}}{{#isEnum}}{{#isListContainer}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.map({$0.rawValue}).encodeToJSON(){{/isListContainer}}{{#isMapContainer}}//TODO: handle enum map scenario{{/isMapContainer}}{{/isEnum}}{{/isContainer}}{{/vars}}
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
{{/vars.isEmpty}}
{{/isEnum}}
{{/isArrayModel}}
{{/model}}
{{/models}}

View File

@ -56,6 +56,8 @@ public class JavaClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;
//clientCodegen.setSupportJava6(Boolean.valueOf(JavaOptionsProvider.SUPPORT_JAVA6));
//times = 1;
}};
}
}

View File

@ -17,6 +17,7 @@ public class JavaClientOptionsProvider extends JavaOptionsProvider {
options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE);
options.put(JavaClientCodegen.USE_RX_JAVA, "false");
options.put(JavaClientCodegen.PARCELABLE_MODEL, "false");
options.put(JavaClientCodegen.SUPPORT_JAVA6, "false");
return options;
}

View File

@ -19,6 +19,7 @@ public class JavaOptionsProvider implements OptionsProvider {
public static final String SERIALIZABLE_MODEL_VALUE = "false";
public static final String FULL_JAVA_UTIL_VALUE = "true";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
//public static final String SUPPORT_JAVA6 = "true";
private ImmutableMap<String, String> options;
@ -42,6 +43,7 @@ public class JavaOptionsProvider implements OptionsProvider {
.put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true")
.put(JavaClientCodegen.DATE_LIBRARY, "joda")
.put("hideGenerationTimestamp", "true")
//.put("supportJava6", "true")
.build();
}

View File

@ -0,0 +1,63 @@
package io.swagger.codegen.options;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.Swift3Codegen;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class Swift3OptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String PROJECT_NAME_VALUE = "Swagger";
public static final String RESPONSE_AS_VALUE = "test";
public static final String UNWRAP_REQUIRED_VALUE = "true";
public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," +
" :tag => 'v1.0.0-SNAPSHOT' }";
public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT";
public static final String POD_AUTHORS_VALUE = "podAuthors";
public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL";
public static final String POD_DOCSET_URL_VALUE = "podDocsetURL";
public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'";
public static final String POD_HOMEPAGE_VALUE = "podHomepage";
public static final String POD_SUMMARY_VALUE = "podSummary";
public static final String POD_DESCRIPTION_VALUE = "podDescription";
public static final String POD_SCREENSHOTS_VALUE = "podScreenshots";
public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL";
public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace";
@Override
public String getLanguage() {
return "swift";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(Swift3Codegen.PROJECT_NAME, PROJECT_NAME_VALUE)
.put(Swift3Codegen.RESPONSE_AS, RESPONSE_AS_VALUE)
.put(Swift3Codegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE)
.put(Swift3Codegen.POD_SOURCE, POD_SOURCE_VALUE)
.put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE)
.put(Swift3Codegen.POD_AUTHORS, POD_AUTHORS_VALUE)
.put(Swift3Codegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE)
.put(Swift3Codegen.POD_DOCSET_URL, POD_DOCSET_URL_VALUE)
.put(Swift3Codegen.POD_LICENSE, POD_LICENSE_VALUE)
.put(Swift3Codegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE)
.put(Swift3Codegen.POD_SUMMARY, POD_SUMMARY_VALUE)
.put(Swift3Codegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE)
.put(Swift3Codegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE)
.put(Swift3Codegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE)
.put(Swift3Codegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE)
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -0,0 +1,91 @@
package io.swagger.codegen.swift3;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.languages.Swift3Codegen;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Swift3CodegenTest {
Swift3Codegen swiftCodegen = new Swift3Codegen();
@Test
public void shouldNotBreakCorrectName() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName");
}
@Test
public void testSingleWordAllCaps() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value");
}
@Test
public void testSingleWordLowercase() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value");
}
@Test
public void testCapitalsWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName");
}
@Test
public void testCapitalsWithDash() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName");
}
@Test
public void testCapitalsWithSpace() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName");
}
@Test
public void testLowercaseWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName");
}
@Test(description = "returns NSData when response format is binary")
public void binaryDataTest() {
final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json");
final DefaultCodegen codegen = new Swift3Codegen();
final String path = "/tests/binaryResponse";
final Operation p = model.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions());
Assert.assertEquals(op.returnType, "Data");
Assert.assertEquals(op.bodyParam.dataType, "Data");
Assert.assertTrue(op.bodyParam.isBinary);
Assert.assertTrue(op.responses.get(0).isBinary);
}
@Test
public void testDefaultPodAuthors() throws Exception {
// Given
// When
swiftCodegen.processOpts();
// Then
final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS);
Assert.assertEquals(podAuthors, Swift3Codegen.DEFAULT_POD_AUTHORS);
}
@Test
public void testPodAuthors() throws Exception {
// Given
final String swaggerDevs = "Swagger Devs";
swiftCodegen.additionalProperties().put(Swift3Codegen.POD_AUTHORS, swaggerDevs);
// When
swiftCodegen.processOpts();
// Then
final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS);
Assert.assertEquals(podAuthors, swaggerDevs);
}
}

View File

@ -0,0 +1,101 @@
package io.swagger.codegen.swift3;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.languages.Swift3Codegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class Swift3ModelTest {
@Test(description = "convert a simple java model")
public void simpleModelTest() {
final Model model = new ModelImpl()
.description("a sample model")
.property("id", new LongProperty())
.property("name", new StringProperty())
.property("createdAt", new DateTimeProperty())
.property("binary", new BinaryProperty())
.property("byte", new ByteArrayProperty())
.property("uuid", new UUIDProperty())
.required("id")
.required("name")
.discriminator("test");
final DefaultCodegen codegen = new Swift3Codegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 6);
Assert.assertEquals(cm.discriminator,"test");
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.datatype, "Int64");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "Int64");
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertTrue(property1.isNotContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.datatype, "String");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "String");
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isNotContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.datatype, "Date");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "Date");
Assert.assertTrue(property3.hasMore);
Assert.assertNull(property3.required);
Assert.assertTrue(property3.isNotContainer);
final CodegenProperty property4 = cm.vars.get(3);
Assert.assertEquals(property4.baseName, "binary");
Assert.assertEquals(property4.datatype, "Data");
Assert.assertEquals(property4.name, "binary");
Assert.assertNull(property4.defaultValue);
Assert.assertEquals(property4.baseType, "Data");
Assert.assertTrue(property4.hasMore);
Assert.assertNull(property4.required);
Assert.assertTrue(property4.isNotContainer);
final CodegenProperty property5 = cm.vars.get(4);
Assert.assertEquals(property5.baseName, "byte");
Assert.assertEquals(property5.datatype, "Data");
Assert.assertEquals(property5.name, "byte");
Assert.assertNull(property5.defaultValue);
Assert.assertEquals(property5.baseType, "Data");
Assert.assertTrue(property5.hasMore);
Assert.assertNull(property5.required);
Assert.assertTrue(property5.isNotContainer);
final CodegenProperty property6 = cm.vars.get(5);
Assert.assertEquals(property6.baseName, "uuid");
Assert.assertEquals(property6.datatype, "UUID");
Assert.assertEquals(property6.name, "uuid");
Assert.assertNull(property6.defaultValue);
Assert.assertEquals(property6.baseType, "UUID");
Assert.assertNull(property6.hasMore);
Assert.assertNull(property6.required);
Assert.assertTrue(property6.isNotContainer);
}
}

View File

@ -0,0 +1,38 @@
package io.swagger.codegen.swift3;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.Swift3Codegen;
import io.swagger.codegen.options.Swift3OptionsProvider;
import mockit.Expectations;
import mockit.Tested;
public class Swift3OptionsTest extends AbstractOptionsTest {
@Tested
private Swift3Codegen clientCodegen;
public Swift3OptionsTest() {
super(new Swift3OptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Swift3OptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setProjectName(Swift3OptionsProvider.PROJECT_NAME_VALUE);
times = 1;
clientCodegen.setResponseAs(Swift3OptionsProvider.RESPONSE_AS_VALUE.split(","));
times = 1;
clientCodegen.setUnwrapRequired(Boolean.valueOf(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE));
times = 1;
}};
}
}

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View File

@ -25,7 +25,7 @@
/*
* SWGApiResponse.h
*
*
* Describes the result of uploading an image resource
*/
#ifndef SWGApiResponse_H_

View File

@ -25,7 +25,7 @@
/*
* SWGCategory.h
*
*
* A category for a pet
*/
#ifndef SWGCategory_H_

View File

@ -117,6 +117,27 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
qDebug() << "Can't set value because the target pointer is NULL";
}
}
else if (QStringLiteral("QByteArray").compare(type) == 0) {
QByteArray **val = static_cast<QByteArray**>(value);
if(val != NULL) {
if(!obj.isNull()) {
// create a new value and return
delete *val;
*val = new QByteArray(QByteArray::fromBase64(QByteArray::fromStdString(obj.toString().toStdString())));
return;
}
else {
// set target to NULL
delete *val;
*val = NULL;
}
}
else {
qDebug() << "Can't set value because the target pointer is NULL";
}
}
else if(type.startsWith("SWG") && obj.isObject()) {
// complex type
QJsonObject jsonObj = obj.toObject();
@ -244,6 +265,10 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
QDateTime* datetime = static_cast<QDateTime*>(value);
output->insert(name, QJsonValue(datetime->toString(Qt::ISODate)));
}
else if(QStringLiteral("QByteArray").compare(type) == 0) {
QByteArray* byteArray = static_cast<QByteArray*>(value);
output->insert(name, QJsonValue(QString(byteArray->toBase64())));
}
}
void

View File

@ -51,9 +51,9 @@ SWGOrder::~SWGOrder() {
void
SWGOrder::init() {
id = 0L;
petId = 0L;
pet_id = 0L;
quantity = 0;
shipDate = NULL;
ship_date = NULL;
status = new QString("");
complete = false;
}
@ -63,8 +63,8 @@ SWGOrder::cleanup() {
if(shipDate != NULL) {
delete shipDate;
if(ship_date != NULL) {
delete ship_date;
}
if(status != NULL) {
delete status;
@ -84,9 +84,9 @@ SWGOrder::fromJson(QString &json) {
void
SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&petId, pJson["petId"], "qint64", "");
setValue(&pet_id, pJson["pet_id"], "qint64", "");
setValue(&quantity, pJson["quantity"], "qint32", "");
setValue(&shipDate, pJson["shipDate"], "QDateTime", "QDateTime");
setValue(&ship_date, pJson["ship_date"], "QDateTime", "QDateTime");
setValue(&status, pJson["status"], "QString", "QString");
setValue(&complete, pJson["complete"], "bool", "");
}
@ -105,11 +105,11 @@ QJsonObject*
SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id));
obj->insert("petId", QJsonValue(petId));
obj->insert("pet_id", QJsonValue(pet_id));
obj->insert("quantity", QJsonValue(quantity));
toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime"));
toJsonValue(QString("ship_date"), ship_date, obj, QString("QDateTime"));
@ -133,11 +133,11 @@ SWGOrder::setId(qint64 id) {
qint64
SWGOrder::getPetId() {
return petId;
return pet_id;
}
void
SWGOrder::setPetId(qint64 petId) {
this->petId = petId;
SWGOrder::setPetId(qint64 pet_id) {
this->pet_id = pet_id;
}
qint32
@ -151,11 +151,11 @@ SWGOrder::setQuantity(qint32 quantity) {
QDateTime*
SWGOrder::getShipDate() {
return shipDate;
return ship_date;
}
void
SWGOrder::setShipDate(QDateTime* shipDate) {
this->shipDate = shipDate;
SWGOrder::setShipDate(QDateTime* ship_date) {
this->ship_date = ship_date;
}
QString*

View File

@ -25,7 +25,7 @@
/*
* SWGOrder.h
*
*
* An order for a pets from the pet store
*/
#ifndef SWGOrder_H_
@ -58,11 +58,11 @@ public:
qint64 getId();
void setId(qint64 id);
qint64 getPetId();
void setPetId(qint64 petId);
void setPetId(qint64 pet_id);
qint32 getQuantity();
void setQuantity(qint32 quantity);
QDateTime* getShipDate();
void setShipDate(QDateTime* shipDate);
void setShipDate(QDateTime* ship_date);
QString* getStatus();
void setStatus(QString* status);
bool getComplete();
@ -70,9 +70,9 @@ bool getComplete();
private:
qint64 id;
qint64 petId;
qint64 pet_id;
qint32 quantity;
QDateTime* shipDate;
QDateTime* ship_date;
QString* status;
bool complete;
};

View File

@ -53,7 +53,7 @@ SWGPet::init() {
id = 0L;
category = new SWGCategory();
name = new QString("");
photoUrls = new QList<QString*>();
photo_urls = new QList<QString*>();
tags = new QList<SWGTag*>();
status = new QString("");
}
@ -67,12 +67,12 @@ if(category != NULL) {
if(name != NULL) {
delete name;
}
if(photoUrls != NULL) {
QList<QString*>* arr = photoUrls;
if(photo_urls != NULL) {
QList<QString*>* arr = photo_urls;
foreach(QString* o, *arr) {
delete o;
}
delete photoUrls;
delete photo_urls;
}
if(tags != NULL) {
QList<SWGTag*>* arr = tags;
@ -100,7 +100,7 @@ SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&category, pJson["category"], "SWGCategory", "SWGCategory");
setValue(&name, pJson["name"], "QString", "QString");
setValue(&photoUrls, pJson["photoUrls"], "QList", "QString");
setValue(&photo_urls, pJson["photo_urls"], "QList", "QString");
setValue(&tags, pJson["tags"], "QList", "SWGTag");
setValue(&status, pJson["status"], "QString", "QString");
}
@ -131,11 +131,11 @@ SWGPet::asJsonObject() {
QList<QString*>* photoUrlsList = photoUrls;
QJsonArray photoUrlsJsonArray;
toJsonArray((QList<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
QList<QString*>* photo_urlsList = photo_urls;
QJsonArray photo_urlsJsonArray;
toJsonArray((QList<void*>*)photo_urls, &photo_urlsJsonArray, "photo_urls", "QString");
obj->insert("photoUrls", photoUrlsJsonArray);
obj->insert("photo_urls", photo_urlsJsonArray);
@ -183,11 +183,11 @@ SWGPet::setName(QString* name) {
QList<QString*>*
SWGPet::getPhotoUrls() {
return photoUrls;
return photo_urls;
}
void
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->photoUrls = photoUrls;
SWGPet::setPhotoUrls(QList<QString*>* photo_urls) {
this->photo_urls = photo_urls;
}
QList<SWGTag*>*

View File

@ -25,7 +25,7 @@
/*
* SWGPet.h
*
*
* A pet for sale in the pet store
*/
#ifndef SWGPet_H_
@ -64,7 +64,7 @@ SWGCategory* getCategory();
QString* getName();
void setName(QString* name);
QList<QString*>* getPhotoUrls();
void setPhotoUrls(QList<QString*>* photoUrls);
void setPhotoUrls(QList<QString*>* photo_urls);
QList<SWGTag*>* getTags();
void setTags(QList<SWGTag*>* tags);
QString* getStatus();
@ -74,7 +74,7 @@ private:
qint64 id;
SWGCategory* category;
QString* name;
QList<QString*>* photoUrls;
QList<QString*>* photo_urls;
QList<SWGTag*>* tags;
QString* status;
};

View File

@ -81,12 +81,12 @@ SWGPetApi::addPetCallback(HttpRequestWorker * worker) {
emit addPetSignal();
}
void
SWGPetApi::deletePet(qint64 petId, QString* apiKey) {
SWGPetApi::deletePet(qint64 pet_id, QString* api_key) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
QString pet_idPathParam("{"); pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, stringValue(pet_id));
HttpRequestWorker *worker = new HttpRequestWorker();
@ -315,12 +315,12 @@ SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) {
}
void
SWGPetApi::getPetById(qint64 petId) {
SWGPetApi::getPetById(qint64 pet_id) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
QString pet_idPathParam("{"); pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, stringValue(pet_id));
HttpRequestWorker *worker = new HttpRequestWorker();
@ -400,12 +400,12 @@ SWGPetApi::updatePetCallback(HttpRequestWorker * worker) {
emit updatePetSignal();
}
void
SWGPetApi::updatePetWithForm(qint64 petId, QString* name, QString* status) {
SWGPetApi::updatePetWithForm(qint64 pet_id, QString* name, QString* status) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
QString pet_idPathParam("{"); pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, stringValue(pet_id));
HttpRequestWorker *worker = new HttpRequestWorker();
@ -447,19 +447,19 @@ SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) {
emit updatePetWithFormSignal();
}
void
SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file) {
SWGPetApi::uploadFile(qint64 pet_id, QString* additional_metadata, SWGHttpRequestInputFileElement* file) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
QString pet_idPathParam("{"); pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, stringValue(pet_id));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
if (additionalMetadata != NULL) {
input.add_var("additionalMetadata", *additionalMetadata);
if (additional_metadata != NULL) {
input.add_var("additionalMetadata", *additional_metadata);
}
if (file != NULL) {
input.add_file("file", (*file).local_filename, (*file).request_filename, (*file).mime_type);

View File

@ -48,13 +48,13 @@ public:
QString basePath;
void addPet(SWGPet body);
void deletePet(qint64 petId, QString* apiKey);
void deletePet(qint64 pet_id, QString* api_key);
void findPetsByStatus(QList<QString*>* status);
void findPetsByTags(QList<QString*>* tags);
void getPetById(qint64 petId);
void getPetById(qint64 pet_id);
void updatePet(SWGPet body);
void updatePetWithForm(qint64 petId, QString* name, QString* status);
void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file);
void updatePetWithForm(qint64 pet_id, QString* name, QString* status);
void uploadFile(qint64 pet_id, QString* additional_metadata, SWGHttpRequestInputFileElement* file);
private:
void addPetCallback (HttpRequestWorker * worker);

View File

@ -40,12 +40,12 @@ SWGStoreApi::SWGStoreApi(QString host, QString basePath) {
}
void
SWGStoreApi::deleteOrder(QString* orderId) {
SWGStoreApi::deleteOrder(QString* order_id) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
QString order_idPathParam("{"); order_idPathParam.append("orderId").append("}");
fullPath.replace(order_idPathParam, stringValue(order_id));
HttpRequestWorker *worker = new HttpRequestWorker();
@ -135,12 +135,12 @@ SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) {
}
void
SWGStoreApi::getOrderById(qint64 orderId) {
SWGStoreApi::getOrderById(qint64 order_id) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
QString order_idPathParam("{"); order_idPathParam.append("orderId").append("}");
fullPath.replace(order_idPathParam, stringValue(order_id));
HttpRequestWorker *worker = new HttpRequestWorker();

View File

@ -46,9 +46,9 @@ public:
QString host;
QString basePath;
void deleteOrder(QString* orderId);
void deleteOrder(QString* order_id);
void getInventory();
void getOrderById(qint64 orderId);
void getOrderById(qint64 order_id);
void placeOrder(SWGOrder body);
private:

View File

@ -25,7 +25,7 @@
/*
* SWGTag.h
*
*
* A tag for a pet
*/
#ifndef SWGTag_H_

View File

@ -52,12 +52,12 @@ void
SWGUser::init() {
id = 0L;
username = new QString("");
firstName = new QString("");
lastName = new QString("");
first_name = new QString("");
last_name = new QString("");
email = new QString("");
password = new QString("");
phone = new QString("");
userStatus = 0;
user_status = 0;
}
void
@ -66,11 +66,11 @@ SWGUser::cleanup() {
if(username != NULL) {
delete username;
}
if(firstName != NULL) {
delete firstName;
if(first_name != NULL) {
delete first_name;
}
if(lastName != NULL) {
delete lastName;
if(last_name != NULL) {
delete last_name;
}
if(email != NULL) {
delete email;
@ -97,12 +97,12 @@ void
SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&username, pJson["username"], "QString", "QString");
setValue(&firstName, pJson["firstName"], "QString", "QString");
setValue(&lastName, pJson["lastName"], "QString", "QString");
setValue(&first_name, pJson["first_name"], "QString", "QString");
setValue(&last_name, pJson["last_name"], "QString", "QString");
setValue(&email, pJson["email"], "QString", "QString");
setValue(&password, pJson["password"], "QString", "QString");
setValue(&phone, pJson["phone"], "QString", "QString");
setValue(&userStatus, pJson["userStatus"], "qint32", "");
setValue(&user_status, pJson["user_status"], "qint32", "");
}
QString
@ -126,12 +126,12 @@ SWGUser::asJsonObject() {
toJsonValue(QString("firstName"), firstName, obj, QString("QString"));
toJsonValue(QString("first_name"), first_name, obj, QString("QString"));
toJsonValue(QString("lastName"), lastName, obj, QString("QString"));
toJsonValue(QString("last_name"), last_name, obj, QString("QString"));
@ -149,7 +149,7 @@ SWGUser::asJsonObject() {
toJsonValue(QString("phone"), phone, obj, QString("QString"));
obj->insert("userStatus", QJsonValue(userStatus));
obj->insert("user_status", QJsonValue(user_status));
return obj;
}
@ -174,20 +174,20 @@ SWGUser::setUsername(QString* username) {
QString*
SWGUser::getFirstName() {
return firstName;
return first_name;
}
void
SWGUser::setFirstName(QString* firstName) {
this->firstName = firstName;
SWGUser::setFirstName(QString* first_name) {
this->first_name = first_name;
}
QString*
SWGUser::getLastName() {
return lastName;
return last_name;
}
void
SWGUser::setLastName(QString* lastName) {
this->lastName = lastName;
SWGUser::setLastName(QString* last_name) {
this->last_name = last_name;
}
QString*
@ -219,11 +219,11 @@ SWGUser::setPhone(QString* phone) {
qint32
SWGUser::getUserStatus() {
return userStatus;
return user_status;
}
void
SWGUser::setUserStatus(qint32 userStatus) {
this->userStatus = userStatus;
SWGUser::setUserStatus(qint32 user_status) {
this->user_status = user_status;
}

View File

@ -25,7 +25,7 @@
/*
* SWGUser.h
*
*
* A User who is purchasing from the pet store
*/
#ifndef SWGUser_H_
@ -59,9 +59,9 @@ public:
QString* getUsername();
void setUsername(QString* username);
QString* getFirstName();
void setFirstName(QString* firstName);
void setFirstName(QString* first_name);
QString* getLastName();
void setLastName(QString* lastName);
void setLastName(QString* last_name);
QString* getEmail();
void setEmail(QString* email);
QString* getPassword();
@ -69,17 +69,17 @@ QString* getPassword();
QString* getPhone();
void setPhone(QString* phone);
qint32 getUserStatus();
void setUserStatus(qint32 userStatus);
void setUserStatus(qint32 user_status);
private:
qint64 id;
QString* username;
QString* firstName;
QString* lastName;
QString* first_name;
QString* last_name;
QString* email;
QString* password;
QString* phone;
qint32 userStatus;
qint32 user_status;
};
} /* namespace Swagger */

View File

@ -1,8 +1,8 @@
package io.swagger.api;
import io.swagger.model.Pet;
import java.io.File;
import io.swagger.model.ModelApiResponse;
import java.io.File;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
@ -33,10 +33,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> addPet(
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body
);
ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = {
@ -51,13 +48,8 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deletePet(
@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey
);
ResponseEntity<Void> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey);
@ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = {
@ -73,10 +65,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status
);
ResponseEntity<List<Pet>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status);
@ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = {
@ -92,10 +81,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags
);
ResponseEntity<List<Pet>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags);
@ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = {
@ -109,10 +95,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Pet> getPetById(
@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId
);
ResponseEntity<Pet> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId);
@ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = {
@ -129,10 +112,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updatePet(
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body
);
ResponseEntity<Void> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = {
@ -147,16 +127,9 @@ public interface PetApi {
produces = "application/json",
consumes = "application/x-www-form-urlencoded",
method = RequestMethod.POST)
ResponseEntity<Void> updatePetWithForm(
@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,
@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status);
ResponseEntity<Void> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,
@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status);
@ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
@ -171,15 +144,8 @@ public interface PetApi {
produces = "application/json",
consumes = "multipart/form-data",
method = RequestMethod.POST)
ResponseEntity<ModelApiResponse> uploadFile(
@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,
@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file);
ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,
@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file);
}

View File

@ -28,10 +28,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteOrder(
@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId
);
ResponseEntity<Void> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId);
@ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = {
@ -55,10 +52,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId
);
ResponseEntity<Order> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId);
@ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", })
@ -69,9 +63,6 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Order> placeOrder(
@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body
);
ResponseEntity<Order> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body);
}

View File

@ -27,10 +27,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUser(
@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body
);
ResponseEntity<Void> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -40,10 +37,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithArrayInput(
@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body
);
ResponseEntity<Void> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -53,10 +47,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithListInput(
@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body
);
ResponseEntity<Void> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", })
@ -67,10 +58,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteUser(
@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username
);
ResponseEntity<Void> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", })
@ -82,10 +70,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<User> getUserByName(
@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username
);
ResponseEntity<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", })
@ -96,13 +81,8 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<String> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username
,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password
);
ResponseEntity<String> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,
@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password);
@ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", })
@ -123,12 +103,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updateUser(
@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username
,
@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body
);
ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,
@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body);
}

View File

@ -1,8 +1,8 @@
package io.swagger.api;
import io.swagger.model.Pet;
import java.io.File;
import io.swagger.model.ModelApiResponse;
import java.io.File;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
@ -33,11 +33,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> addPet(
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body
);
ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = {
@ -52,15 +48,8 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deletePet(
@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey
);
ResponseEntity<Void> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey);
@ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = {
@ -76,11 +65,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status
);
ResponseEntity<List<Pet>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status);
@ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = {
@ -96,11 +81,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags
);
ResponseEntity<List<Pet>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags);
@ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = {
@ -114,11 +95,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Pet> getPetById(
@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId
);
ResponseEntity<Pet> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId);
@ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = {
@ -135,11 +112,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updatePet(
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body
);
ResponseEntity<Void> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = {
@ -154,19 +127,9 @@ public interface PetApi {
produces = "application/json",
consumes = "application/x-www-form-urlencoded",
method = RequestMethod.POST)
ResponseEntity<Void> updatePetWithForm(
@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name
,
@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status
);
ResponseEntity<Void> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,
@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status);
@ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
@ -181,18 +144,8 @@ public interface PetApi {
produces = "application/json",
consumes = "multipart/form-data",
method = RequestMethod.POST)
ResponseEntity<ModelApiResponse> uploadFile(
@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId
,
@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata
,
@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file
);
ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,
@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file);
}

View File

@ -28,11 +28,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteOrder(
@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId
);
ResponseEntity<Void> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId);
@ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = {
@ -56,11 +52,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId
);
ResponseEntity<Order> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId);
@ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", })
@ -71,10 +63,6 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Order> placeOrder(
@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body
);
ResponseEntity<Order> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body);
}

View File

@ -27,11 +27,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUser(
@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body
);
ResponseEntity<Void> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -41,11 +37,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithArrayInput(
@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body
);
ResponseEntity<Void> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -55,11 +47,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithListInput(
@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body
);
ResponseEntity<Void> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", })
@ -70,11 +58,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteUser(
@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username
);
ResponseEntity<Void> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", })
@ -86,11 +70,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<User> getUserByName(
@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username
);
ResponseEntity<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", })
@ -101,15 +81,8 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<String> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username
,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password
);
ResponseEntity<String> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,
@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password);
@ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", })
@ -130,14 +103,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updateUser(
@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username
,
@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body
);
ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,
@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body);
}

View File

@ -0,0 +1,63 @@
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
## Other
*.xccheckout
*.moved-aside
*.xcuserstate
*.xcscmblueprint
## Obj-C/Swift specific
*.hmap
*.ipa
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
.build/
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
fastlane/report.xml
fastlane/screenshots

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,63 @@
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
## Other
*.xccheckout
*.moved-aside
*.xcuserstate
*.xcscmblueprint
## Obj-C/Swift specific
*.hmap
*.ipa
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
.build/
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
fastlane/report.xml
fastlane/screenshots

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
github "Alamofire/Alamofire" >= 3.1.0

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View File

@ -0,0 +1,13 @@
Pod::Spec.new do |s|
s.name = 'PetstoreClient'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.version = '0.0.1'
s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }
s.authors = ''
s.license = 'Apache License, Version 2.0'
s.homepage = 'https://github.com/swagger-api/swagger-codegen'
s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
s.dependency 'Alamofire', '~> 4.0'
end

View File

@ -0,0 +1,42 @@
// APIHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
class APIHelper {
static func rejectNil(_ source: [String:Any?]) -> [String:Any]? {
var destination = [String:Any]()
for (key, nillableValue) in source {
if let value: Any = nillableValue {
destination[key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? {
guard let source = source else {
return nil
}
var destination = [String:Any]()
let theTrue = NSNumber(value: true as Bool)
let theFalse = NSNumber(value: false as Bool)
for (key, value) in source {
switch value {
case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse:
destination[key] = "\(value as! Bool)" as Any?
default:
destination[key] = value
}
}
return destination
}
}

View File

@ -0,0 +1,76 @@
// APIs.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class PetstoreClientAPI {
open static var basePath = "http://petstore.swagger.io/v2"
open static var credential: URLCredential?
open static var customHeaders: [String:String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
open class APIBase {
func toParameters(_ encodable: JSONEncodable?) -> [String: Any]? {
let encoded: Any? = encodable?.encodeToJSON()
if encoded! is [Any] {
var dictionary = [String:Any]()
for (index, item) in (encoded as! [Any]).enumerated() {
dictionary["\(index)"] = item
}
return dictionary
} else {
return encoded as? [String:Any]
}
}
}
open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String:String] = [:]
let parameters: [String:Any]?
let isBody: Bool
let method: String
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((Progress) -> ())?
required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
addHeaders(PetstoreClientAPI.customHeaders)
}
open func addHeaders(_ aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) { }
public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
open func addCredential() -> Self {
self.credential = PetstoreClientAPI.credential
return self
}
}
public protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -0,0 +1,214 @@
//
// FakeAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class FakeAPI: APIBase {
/**
To test \"client\" model
- parameter body: (body) client model
- parameter completion: completion handler to receive the data and the error objects
*/
open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) {
testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
To test \"client\" model
- PATCH /fake
- examples: [{contentType=application/json, example={
"client" : "aeiou"
}}]
- parameter body: (body) client model
- returns: RequestBuilder<Client>
*/
open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder<Client> {
let path = "/fake"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Client>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Fake endpoint for testing various parameters
- parameter number: (form) None
- parameter double: (form) None
- parameter patternWithoutDelimiter: (form) None
- parameter byte: (form) None
- parameter integer: (form) None (optional)
- parameter int32: (form) None (optional)
- parameter int64: (form) None (optional)
- parameter float: (form) None (optional)
- parameter string: (form) None (optional)
- parameter binary: (form) None (optional)
- parameter date: (form) None (optional)
- parameter dateTime: (form) None (optional)
- parameter password: (form) None (optional)
- parameter callback: (form) None (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) {
testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in
completion(error);
}
}
/**
Fake endpoint for testing various parameters
- POST /fake
- Fake endpoint for testing various parameters
- BASIC:
- type: basic
- name: http_basic_test
- parameter number: (form) None
- parameter double: (form) None
- parameter patternWithoutDelimiter: (form) None
- parameter byte: (form) None
- parameter integer: (form) None (optional)
- parameter int32: (form) None (optional)
- parameter int64: (form) None (optional)
- parameter float: (form) None (optional)
- parameter string: (form) None (optional)
- parameter binary: (form) None (optional)
- parameter date: (form) None (optional)
- parameter dateTime: (form) None (optional)
- parameter password: (form) None (optional)
- parameter callback: (form) None (optional)
- returns: RequestBuilder<Void>
*/
open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder<Void> {
let path = "/fake"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"integer": integer?.encodeToJSON(),
"int32": int32?.encodeToJSON(),
"int64": int64?.encodeToJSON(),
"number": number,
"float": float,
"double": double,
"string": string,
"pattern_without_delimiter": patternWithoutDelimiter,
"byte": byte,
"binary": binary,
"date": date?.encodeToJSON(),
"dateTime": dateTime?.encodeToJSON(),
"password": password,
"callback": callback
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
* enum for parameter enumFormStringArray
*/
public enum EnumFormStringArray_testEnumParameters: String {
case greaterThan = ">"
case dollar = "$"
}
/**
* enum for parameter enumFormString
*/
public enum EnumFormString_testEnumParameters: String {
case abc = "_abc"
case efg = "-efg"
case xyz = "(xyz)"
}
/**
* enum for parameter enumQueryStringArray
*/
public enum EnumQueryStringArray_testEnumParameters: String {
case greaterThan = ">"
case dollar = "$"
}
/**
* enum for parameter enumQueryString
*/
public enum EnumQueryString_testEnumParameters: String {
case abc = "_abc"
case efg = "-efg"
case xyz = "(xyz)"
}
/**
To test enum parameters
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg)
- parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg)
- parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
- parameter enumQueryDouble: (form) Query parameter enum test (double) (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) {
testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in
completion(error);
}
}
/**
To test enum parameters
- GET /fake
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg)
- parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg)
- parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
- parameter enumQueryDouble: (form) Query parameter enum test (double) (optional)
- returns: RequestBuilder<Void>
*/
open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder<Void> {
let path = "/fake"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"enum_query_string_array": enumQueryStringArray,
"enum_query_string": enumQueryString?.rawValue,
"enum_query_integer": enumQueryInteger
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}

View File

@ -0,0 +1,49 @@
//
// FakeclassnametagsAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class FakeclassnametagsAPI: APIBase {
/**
To test class name in snake case
- parameter body: (body) client model
- parameter completion: completion handler to receive the data and the error objects
*/
open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) {
testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
To test class name in snake case
- PATCH /fake_classname_test
- examples: [{contentType=application/json, example={
"client" : "aeiou"
}}]
- parameter body: (body) client model
- returns: RequestBuilder<Client>
*/
open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder<Client> {
let path = "/fake_classname_test"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Client>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}

View File

@ -0,0 +1,501 @@
//
// PetAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class PetAPI: APIBase {
/**
Add a new pet to the store
- parameter body: (body) Pet object that needs to be added to the store
- parameter completion: completion handler to receive the data and the error objects
*/
open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) {
addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Add a new pet to the store
- POST /pet
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deletePet(petId: Int64, completion: @escaping ((_ error: Error?) -> Void)) {
deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
completion(error);
}
}
/**
Deletes a pet
- DELETE /pet/{petId}
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- returns: RequestBuilder<Void>
*/
open class func deletePetWithRequestBuilder(petId: Int64) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
* enum for parameter status
*/
public enum Status_findPetsByStatus: String {
case available = "available"
case pending = "pending"
case sold = "sold"
}
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter
- parameter completion: completion handler to receive the data and the error objects
*/
open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) {
findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Finds Pets by status
- GET /pet/findByStatus
- Multiple status values can be provided with comma separated strings
- OAuth:
- type: oauth2
- name: petstore_auth
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example=[ {
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
} ]}]
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example=[ {
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
} ]}]
- parameter status: (query) Status values that need to be considered for filter
- returns: RequestBuilder<[Pet]>
*/
open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> {
let path = "/pet/findByStatus"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"status": status
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by
- parameter completion: completion handler to receive the data and the error objects
*/
open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) {
findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Finds Pets by tags
- GET /pet/findByTags
- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
- OAuth:
- type: oauth2
- name: petstore_auth
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example=[ {
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
} ]}]
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example=[ {
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
} ]}]
- parameter tags: (query) Tags to filter by
- returns: RequestBuilder<[Pet]>
*/
open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> {
let path = "/pet/findByTags"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"tags": tags
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Find pet by ID
- parameter petId: (path) ID of pet to return
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) {
getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Find pet by ID
- GET /pet/{petId}
- Returns a single pet
- API Key:
- type: apiKey api_key
- name: api_key
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example={
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
}}]
- examples: [{contentType=application/xml, example=<Pet>
<id>123456</id>
<name>doggie</name>
<photoUrls>
<photoUrls>string</photoUrls>
</photoUrls>
<tags>
</tags>
<status>string</status>
</Pet>}, {contentType=application/json, example={
"photoUrls" : [ "aeiou" ],
"name" : "doggie",
"id" : 123456789,
"category" : {
"name" : "aeiou",
"id" : 123456789
},
"tags" : [ {
"name" : "aeiou",
"id" : 123456789
} ],
"status" : "aeiou"
}}]
- parameter petId: (path) ID of pet to return
- returns: RequestBuilder<Pet>
*/
open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder<Pet> {
var path = "/pet/{petId}"
path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Update an existing pet
- parameter body: (body) Pet object that needs to be added to the store
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) {
updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Update an existing pet
- PUT /pet
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) {
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in
completion(error);
}
}
/**
Updates a pet in the store with form data
- POST /pet/{petId}
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: RequestBuilder<Void>
*/
open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"name": name,
"status": status
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) {
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage
-
- OAuth:
- type: oauth2
- name: petstore_auth
- examples: [{contentType=application/json, example={
"code" : 123,
"type" : "aeiou",
"message" : "aeiou"
}}]
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder<ApiResponse> {
var path = "/pet/{petId}/uploadImage"
path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"additionalMetadata": additionalMetadata,
"file": file
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}

View File

@ -0,0 +1,223 @@
//
// StoreAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class StoreAPI: APIBase {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) {
deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
completion(error);
}
}
/**
Delete purchase order by ID
- DELETE /store/order/{orderId}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder<Void> {
var path = "/store/order/{orderId}"
path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Returns pet inventories by status
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getInventory(completion: @escaping ((_ data: [String:Int32]?,_ error: Error?) -> Void)) {
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Returns pet inventories by status
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key
- name: api_key
- examples: [{contentType=application/json, example={
"key" : 123
}}]
- returns: RequestBuilder<[String:Int32]>
*/
open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> {
let path = "/store/inventory"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) {
getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Find purchase order by ID
- GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- examples: [{contentType=application/xml, example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "aeiou"
}}]
- examples: [{contentType=application/xml, example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "aeiou"
}}]
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder<Order> {
var path = "/store/order/{orderId}"
path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Place an order for a pet
- parameter body: (body) order placed for purchasing the pet
- parameter completion: completion handler to receive the data and the error objects
*/
open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) {
placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Place an order for a pet
- POST /store/order
-
- examples: [{contentType=application/xml, example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "aeiou"
}}]
- examples: [{contentType=application/xml, example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "aeiou"
}}]
- parameter body: (body) order placed for purchasing the pet
- returns: RequestBuilder<Order>
*/
open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder<Order> {
let path = "/store/order"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}

View File

@ -0,0 +1,346 @@
//
// UserAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class UserAPI: APIBase {
/**
Create user
- parameter body: (body) Created user object
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) {
createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Create user
- POST /user
- This can only be done by the logged in user.
- parameter body: (body) Created user object
- returns: RequestBuilder<Void>
*/
open class func createUserWithRequestBuilder(body: User) -> RequestBuilder<Void> {
let path = "/user"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) {
createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Creates list of users with given input array
- POST /user/createWithArray
-
- parameter body: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> {
let path = "/user/createWithArray"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Creates list of users with given input array
- parameter body: (body) List of user object
- parameter completion: completion handler to receive the data and the error objects
*/
open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) {
createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Creates list of users with given input array
- POST /user/createWithList
-
- parameter body: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> {
let path = "/user/createWithList"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) {
deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in
completion(error);
}
}
/**
Delete user
- DELETE /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) The name that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) {
getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Get user by user name
- GET /user/{username}
-
- examples: [{contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>
<password>string</password>
<phone>string</phone>
<userStatus>0</userStatus>
</User>}, {contentType=application/json, example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789,
"email" : "aeiou",
"username" : "aeiou"
}}]
- examples: [{contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>
<password>string</password>
<phone>string</phone>
<userStatus>0</userStatus>
</User>}, {contentType=application/json, example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789,
"email" : "aeiou",
"username" : "aeiou"
}}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
*/
open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> {
var path = "/user/{username}"
path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Logs user into the system
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- parameter completion: completion handler to receive the data and the error objects
*/
open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) {
loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Logs user into the system
- GET /user/login
-
- responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)]
- responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)]
- examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}]
- examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}]
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- returns: RequestBuilder<String>
*/
open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> {
let path = "/user/login"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [
"username": username,
"password": password
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Logs out current logged in user session
- parameter completion: completion handler to receive the data and the error objects
*/
open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) {
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
completion(error);
}
}
/**
Logs out current logged in user session
- GET /user/logout
-
- returns: RequestBuilder<Void>
*/
open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let path = "/user/logout"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:Any?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) {
updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in
completion(error);
}
}
/**
Updated user
- PUT /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object
- returns: RequestBuilder<Void>
*/
open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}

View File

@ -0,0 +1,191 @@
// AlamofireImplementations.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
}
// Store manager to retain its reference
private var managerStore: [String: Alamofire.SessionManager] = [:]
open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody)
}
/**
May be overridden by a subclass if you want to control the session
configuration.
*/
open func createSessionManager() -> Alamofire.SessionManager {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = buildHeaders()
return Alamofire.SessionManager(configuration: configuration)
}
override open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
let managerId:String = UUID().uuidString
// Create a new manager for each request to customize its request header
let manager = createSessionManager()
managerStore[managerId] = manager
let encoding:ParameterEncoding = isBody ? JSONEncoding() : URLEncoding()
let xMethod = Alamofire.HTTPMethod(rawValue: method)
let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(multipartFormData: { mpForm in
for (k, v) in self.parameters! {
switch v {
case let fileURL as URL:
mpForm.append(fileURL, withName: k)
break
case let string as String:
mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k)
break
case let number as NSNumber:
mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k)
break
default:
fatalError("Unprocessable value \(v) with key \(k)")
break
}
}
}, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
if let onProgressReady = self.onProgressReady {
onProgressReady(upload.progress)
}
self.processRequest(request: upload, managerId, completion)
case .failure(let encodingError):
completion(nil, ErrorResponse.Error(415, nil, encodingError))
}
})
} else {
let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request: request, managerId, completion)
}
}
private func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
_ = managerStore.removeValue(forKey: managerId)
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
Response(
response: stringResponse.response!,
body: ((stringResponse.result.value ?? "") as! T)
),
nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
nil,
ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
Response(
response: voidResponse.response!,
body: nil),
nil
)
})
case is Data.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if (dataResponse.result.isFailure) {
completion(
nil,
ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
Response(
response: dataResponse.response!,
body: (dataResponse.data as! T)
),
nil
)
})
default:
validatedRequest.responseJSON(options: .allowFragments) { response in
cleanupRequest()
if response.result.isFailure {
completion(nil, ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!))
return
}
if () is T {
completion(Response(response: response.response!, body: (() as! T)), nil)
return
}
if let json: Any = response.result.value {
let body = Decoders.decode(clazz: T.self, source: json as AnyObject)
completion(Response(response: response.response!, body: body), nil)
return
} else if "" is T {
// swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release
// https://github.com/swagger-api/swagger-parser/pull/34
completion(Response(response: response.response!, body: ("" as! T)), nil)
return
}
completion(nil, ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
}
}
}
private func buildHeaders() -> [String: String] {
var httpHeaders = SessionManager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
}

View File

@ -0,0 +1,86 @@
// Extensions.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
extension Bool: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Float: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int32) }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int64) }
}
extension Double: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension String: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
private func encodeIfPossible<T>(_ object: T) -> Any {
if let encodableObject = object as? JSONEncodable {
return encodableObject.encodeToJSON()
} else {
return object as Any
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> Any {
return self.map(encodeIfPossible)
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> Any {
var dictionary = [AnyHashable: Any]()
for (key, value) in self {
dictionary[key as! NSObject] = encodeIfPossible(value)
}
return dictionary as Any
}
}
extension Data: JSONEncodable {
func encodeToJSON() -> Any {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
private let dateFormatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
fmt.locale = Locale(identifier: "en_US_POSIX")
return fmt
}()
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return dateFormatter.string(from: self) as Any
}
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any {
return self.uuidString
}
}

View File

@ -0,0 +1,598 @@
// Models.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> Any
}
public enum ErrorResponse : Error {
case Error(Int, Data?, Error)
}
open class Response<T> {
open let statusCode: Int
open let header: [String: String]
open let body: T?
public init(statusCode: Int, header: [String: String], body: T?) {
self.statusCode = statusCode
self.header = header
self.body = body
}
public convenience init(response: HTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String:String]()
for (key, value) in rawHeader {
header[key as! String] = value as? String
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
private var once = Int()
class Decoders {
static fileprivate var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static func addDecoder<T>(clazz: T.Type, decoder: @escaping ((AnyObject) -> T)) {
let key = "\(T.self)"
decoders[key] = { decoder($0) as AnyObject }
}
static func decode<T>(clazz: [T].Type, source: AnyObject) -> [T] {
let array = source as! [AnyObject]
return array.map { Decoders.decode(clazz: T.self, source: $0) }
}
static func decode<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject) -> [Key:T] {
let sourceDictionary = source as! [Key: AnyObject]
var dictionary = [Key:T]()
for (key, value) in sourceDictionary {
dictionary[key] = Decoders.decode(clazz: T.self, source: value)
}
return dictionary
}
static func decode<T>(clazz: T.Type, source: AnyObject) -> T {
initialize()
if T.self is Int32.Type && source is NSNumber {
return source.int32Value as! T;
}
if T.self is Int64.Type && source is NSNumber {
return source.int64Value as! T;
}
if T.self is UUID.Type && source is String {
return UUID(uuidString: source as! String) as! T
}
if source is T {
return source as! T
}
if T.self is Data.Type && source is String {
return Data(base64Encoded: source as! String) as! T
}
let key = "\(T.self)"
if let decoder = decoders[key] {
return decoder(source) as! T
} else {
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
}
}
static func decodeOptional<T>(clazz: T.Type, source: AnyObject?) -> T? {
if source is NSNull {
return nil
}
return source.map { (source: AnyObject) -> T in
Decoders.decode(clazz: clazz, source: source)
}
}
static func decodeOptional<T>(clazz: [T].Type, source: AnyObject?) -> [T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
static func decodeOptional<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [Key:T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
private static var __once: () = {
let formatters = [
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS"
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}
// Decoder for Date
Decoders.addDecoder(clazz: Date.self) { (source: AnyObject) -> Date in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.date(from: sourceString) {
return date
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return Date(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
// Decoder for [AdditionalPropertiesClass]
Decoders.addDecoder(clazz: [AdditionalPropertiesClass].self) { (source: AnyObject) -> [AdditionalPropertiesClass] in
return Decoders.decode(clazz: [AdditionalPropertiesClass].self, source: source)
}
// Decoder for AdditionalPropertiesClass
Decoders.addDecoder(clazz: AdditionalPropertiesClass.self) { (source: AnyObject) -> AdditionalPropertiesClass in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = AdditionalPropertiesClass()
instance.mapProperty = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_property"] as AnyObject?)
instance.mapOfMapProperty = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_of_map_property"] as AnyObject?)
return instance
}
// Decoder for [Animal]
Decoders.addDecoder(clazz: [Animal].self) { (source: AnyObject) -> [Animal] in
return Decoders.decode(clazz: [Animal].self, source: source)
}
// Decoder for Animal
Decoders.addDecoder(clazz: Animal.self) { (source: AnyObject) -> Animal in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Animal()
instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?)
instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?)
return instance
}
// Decoder for [AnimalFarm]
Decoders.addDecoder(clazz: [AnimalFarm].self) { (source: AnyObject) -> [AnimalFarm] in
return Decoders.decode(clazz: [AnimalFarm].self, source: source)
}
// Decoder for AnimalFarm
Decoders.addDecoder(clazz: AnimalFarm.self) { (source: AnyObject) -> AnimalFarm in
let sourceArray = source as! [AnyObject]
return sourceArray.map({ Decoders.decode(clazz: Animal.self, source: $0) })
}
// Decoder for [ApiResponse]
Decoders.addDecoder(clazz: [ApiResponse].self) { (source: AnyObject) -> [ApiResponse] in
return Decoders.decode(clazz: [ApiResponse].self, source: source)
}
// Decoder for ApiResponse
Decoders.addDecoder(clazz: ApiResponse.self) { (source: AnyObject) -> ApiResponse in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = ApiResponse()
instance.code = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["code"] as AnyObject?)
instance.type = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["type"] as AnyObject?)
instance.message = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["message"] as AnyObject?)
return instance
}
// Decoder for [ArrayOfArrayOfNumberOnly]
Decoders.addDecoder(clazz: [ArrayOfArrayOfNumberOnly].self) { (source: AnyObject) -> [ArrayOfArrayOfNumberOnly] in
return Decoders.decode(clazz: [ArrayOfArrayOfNumberOnly].self, source: source)
}
// Decoder for ArrayOfArrayOfNumberOnly
Decoders.addDecoder(clazz: ArrayOfArrayOfNumberOnly.self) { (source: AnyObject) -> ArrayOfArrayOfNumberOnly in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = ArrayOfArrayOfNumberOnly()
instance.arrayArrayNumber = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["ArrayArrayNumber"] as AnyObject?)
return instance
}
// Decoder for [ArrayOfNumberOnly]
Decoders.addDecoder(clazz: [ArrayOfNumberOnly].self) { (source: AnyObject) -> [ArrayOfNumberOnly] in
return Decoders.decode(clazz: [ArrayOfNumberOnly].self, source: source)
}
// Decoder for ArrayOfNumberOnly
Decoders.addDecoder(clazz: ArrayOfNumberOnly.self) { (source: AnyObject) -> ArrayOfNumberOnly in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = ArrayOfNumberOnly()
instance.arrayNumber = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["ArrayNumber"] as AnyObject?)
return instance
}
// Decoder for [ArrayTest]
Decoders.addDecoder(clazz: [ArrayTest].self) { (source: AnyObject) -> [ArrayTest] in
return Decoders.decode(clazz: [ArrayTest].self, source: source)
}
// Decoder for ArrayTest
Decoders.addDecoder(clazz: ArrayTest.self) { (source: AnyObject) -> ArrayTest in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = ArrayTest()
instance.arrayOfString = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_of_string"] as AnyObject?)
instance.arrayArrayOfInteger = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_array_of_integer"] as AnyObject?)
instance.arrayArrayOfModel = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_array_of_model"] as AnyObject?)
return instance
}
// Decoder for [Cat]
Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject) -> [Cat] in
return Decoders.decode(clazz: [Cat].self, source: source)
}
// Decoder for Cat
Decoders.addDecoder(clazz: Cat.self) { (source: AnyObject) -> Cat in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Cat()
instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?)
instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?)
instance.declawed = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["declawed"] as AnyObject?)
return instance
}
// Decoder for [Category]
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
return Decoders.decode(clazz: [Category].self, source: source)
}
// Decoder for Category
Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Category()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?)
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?)
return instance
}
// Decoder for [Client]
Decoders.addDecoder(clazz: [Client].self) { (source: AnyObject) -> [Client] in
return Decoders.decode(clazz: [Client].self, source: source)
}
// Decoder for Client
Decoders.addDecoder(clazz: Client.self) { (source: AnyObject) -> Client in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Client()
instance.client = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["client"] as AnyObject?)
return instance
}
// Decoder for [Dog]
Decoders.addDecoder(clazz: [Dog].self) { (source: AnyObject) -> [Dog] in
return Decoders.decode(clazz: [Dog].self, source: source)
}
// Decoder for Dog
Decoders.addDecoder(clazz: Dog.self) { (source: AnyObject) -> Dog in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Dog()
instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?)
instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?)
instance.breed = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["breed"] as AnyObject?)
return instance
}
// Decoder for [EnumArrays]
Decoders.addDecoder(clazz: [EnumArrays].self) { (source: AnyObject) -> [EnumArrays] in
return Decoders.decode(clazz: [EnumArrays].self, source: source)
}
// Decoder for EnumArrays
Decoders.addDecoder(clazz: EnumArrays.self) { (source: AnyObject) -> EnumArrays in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = EnumArrays()
if let justSymbol = sourceDictionary["just_symbol"] as? String {
instance.justSymbol = EnumArrays.JustSymbol(rawValue: (justSymbol))
}
if let arrayEnum = sourceDictionary["array_enum"] as? [String] {
instance.arrayEnum = arrayEnum.map ({ EnumArrays.ArrayEnum(rawValue: $0)! })
}
return instance
}
// Decoder for [EnumClass]
Decoders.addDecoder(clazz: [EnumClass].self) { (source: AnyObject) -> [EnumClass] in
return Decoders.decode(clazz: [EnumClass].self, source: source)
}
// Decoder for EnumClass
Decoders.addDecoder(clazz: EnumClass.self) { (source: AnyObject) -> EnumClass in
if let source = source as? String {
if let result = EnumClass(rawValue: source) {
return result
}
}
fatalError("Source \(source) is not convertible to enum type EnumClass: Maybe swagger file is insufficient")
}
// Decoder for [EnumTest]
Decoders.addDecoder(clazz: [EnumTest].self) { (source: AnyObject) -> [EnumTest] in
return Decoders.decode(clazz: [EnumTest].self, source: source)
}
// Decoder for EnumTest
Decoders.addDecoder(clazz: EnumTest.self) { (source: AnyObject) -> EnumTest in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = EnumTest()
if let enumString = sourceDictionary["enum_string"] as? String {
instance.enumString = EnumTest.EnumString(rawValue: (enumString))
}
if let enumInteger = sourceDictionary["enum_integer"] as? Int32 {
instance.enumInteger = EnumTest.EnumInteger(rawValue: (enumInteger))
}
if let enumNumber = sourceDictionary["enum_number"] as? Double {
instance.enumNumber = EnumTest.EnumNumber(rawValue: (enumNumber))
}
return instance
}
// Decoder for [FormatTest]
Decoders.addDecoder(clazz: [FormatTest].self) { (source: AnyObject) -> [FormatTest] in
return Decoders.decode(clazz: [FormatTest].self, source: source)
}
// Decoder for FormatTest
Decoders.addDecoder(clazz: FormatTest.self) { (source: AnyObject) -> FormatTest in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = FormatTest()
instance.integer = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["integer"] as AnyObject?)
instance.int32 = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["int32"] as AnyObject?)
instance.int64 = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["int64"] as AnyObject?)
instance.number = Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["number"] as AnyObject?)
instance.float = Decoders.decodeOptional(clazz: Float.self, source: sourceDictionary["float"] as AnyObject?)
instance.double = Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["double"] as AnyObject?)
instance.string = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["string"] as AnyObject?)
instance.byte = Decoders.decodeOptional(clazz: Data.self, source: sourceDictionary["byte"] as AnyObject?)
instance.binary = Decoders.decodeOptional(clazz: Data.self, source: sourceDictionary["binary"] as AnyObject?)
instance.date = Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["date"] as AnyObject?)
instance.dateTime = Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["dateTime"] as AnyObject?)
instance.uuid = Decoders.decodeOptional(clazz: UUID.self, source: sourceDictionary["uuid"] as AnyObject?)
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"] as AnyObject?)
return instance
}
// Decoder for [HasOnlyReadOnly]
Decoders.addDecoder(clazz: [HasOnlyReadOnly].self) { (source: AnyObject) -> [HasOnlyReadOnly] in
return Decoders.decode(clazz: [HasOnlyReadOnly].self, source: source)
}
// Decoder for HasOnlyReadOnly
Decoders.addDecoder(clazz: HasOnlyReadOnly.self) { (source: AnyObject) -> HasOnlyReadOnly in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = HasOnlyReadOnly()
instance.bar = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?)
instance.foo = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["foo"] as AnyObject?)
return instance
}
// Decoder for [List]
Decoders.addDecoder(clazz: [List].self) { (source: AnyObject) -> [List] in
return Decoders.decode(clazz: [List].self, source: source)
}
// Decoder for List
Decoders.addDecoder(clazz: List.self) { (source: AnyObject) -> List in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = List()
instance._123List = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["123-list"] as AnyObject?)
return instance
}
// Decoder for [MapTest]
Decoders.addDecoder(clazz: [MapTest].self) { (source: AnyObject) -> [MapTest] in
return Decoders.decode(clazz: [MapTest].self, source: source)
}
// Decoder for MapTest
Decoders.addDecoder(clazz: MapTest.self) { (source: AnyObject) -> MapTest in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = MapTest()
instance.mapMapOfString = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_map_of_string"] as AnyObject?)
if let mapOfEnumString = sourceDictionary["map_of_enum_string"] as? [String:String] { //TODO: handle enum map scenario
}
return instance
}
// Decoder for [MixedPropertiesAndAdditionalPropertiesClass]
Decoders.addDecoder(clazz: [MixedPropertiesAndAdditionalPropertiesClass].self) { (source: AnyObject) -> [MixedPropertiesAndAdditionalPropertiesClass] in
return Decoders.decode(clazz: [MixedPropertiesAndAdditionalPropertiesClass].self, source: source)
}
// Decoder for MixedPropertiesAndAdditionalPropertiesClass
Decoders.addDecoder(clazz: MixedPropertiesAndAdditionalPropertiesClass.self) { (source: AnyObject) -> MixedPropertiesAndAdditionalPropertiesClass in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = MixedPropertiesAndAdditionalPropertiesClass()
instance.uuid = Decoders.decodeOptional(clazz: UUID.self, source: sourceDictionary["uuid"] as AnyObject?)
instance.dateTime = Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["dateTime"] as AnyObject?)
instance.map = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map"] as AnyObject?)
return instance
}
// Decoder for [Model200Response]
Decoders.addDecoder(clazz: [Model200Response].self) { (source: AnyObject) -> [Model200Response] in
return Decoders.decode(clazz: [Model200Response].self, source: source)
}
// Decoder for Model200Response
Decoders.addDecoder(clazz: Model200Response.self) { (source: AnyObject) -> Model200Response in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Model200Response()
instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?)
instance._class = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["class"] as AnyObject?)
return instance
}
// Decoder for [Name]
Decoders.addDecoder(clazz: [Name].self) { (source: AnyObject) -> [Name] in
return Decoders.decode(clazz: [Name].self, source: source)
}
// Decoder for Name
Decoders.addDecoder(clazz: Name.self) { (source: AnyObject) -> Name in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Name()
instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?)
instance.snakeCase = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["snake_case"] as AnyObject?)
instance.property = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["property"] as AnyObject?)
instance._123Number = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["123Number"] as AnyObject?)
return instance
}
// Decoder for [NumberOnly]
Decoders.addDecoder(clazz: [NumberOnly].self) { (source: AnyObject) -> [NumberOnly] in
return Decoders.decode(clazz: [NumberOnly].self, source: source)
}
// Decoder for NumberOnly
Decoders.addDecoder(clazz: NumberOnly.self) { (source: AnyObject) -> NumberOnly in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = NumberOnly()
instance.justNumber = Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["JustNumber"] as AnyObject?)
return instance
}
// Decoder for [Order]
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
return Decoders.decode(clazz: [Order].self, source: source)
}
// Decoder for Order
Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Order()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?)
instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"] as AnyObject?)
instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"] as AnyObject?)
instance.shipDate = Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["shipDate"] as AnyObject?)
if let status = sourceDictionary["status"] as? String {
instance.status = Order.Status(rawValue: (status))
}
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"] as AnyObject?)
return instance
}
// Decoder for [Pet]
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
return Decoders.decode(clazz: [Pet].self, source: source)
}
// Decoder for Pet
Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Pet()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?)
instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"] as AnyObject?)
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?)
instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"] as AnyObject?)
instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"] as AnyObject?)
if let status = sourceDictionary["status"] as? String {
instance.status = Pet.Status(rawValue: (status))
}
return instance
}
// Decoder for [ReadOnlyFirst]
Decoders.addDecoder(clazz: [ReadOnlyFirst].self) { (source: AnyObject) -> [ReadOnlyFirst] in
return Decoders.decode(clazz: [ReadOnlyFirst].self, source: source)
}
// Decoder for ReadOnlyFirst
Decoders.addDecoder(clazz: ReadOnlyFirst.self) { (source: AnyObject) -> ReadOnlyFirst in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = ReadOnlyFirst()
instance.bar = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?)
instance.baz = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["baz"] as AnyObject?)
return instance
}
// Decoder for [Return]
Decoders.addDecoder(clazz: [Return].self) { (source: AnyObject) -> [Return] in
return Decoders.decode(clazz: [Return].self, source: source)
}
// Decoder for Return
Decoders.addDecoder(clazz: Return.self) { (source: AnyObject) -> Return in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Return()
instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"] as AnyObject?)
return instance
}
// Decoder for [SpecialModelName]
Decoders.addDecoder(clazz: [SpecialModelName].self) { (source: AnyObject) -> [SpecialModelName] in
return Decoders.decode(clazz: [SpecialModelName].self, source: source)
}
// Decoder for SpecialModelName
Decoders.addDecoder(clazz: SpecialModelName.self) { (source: AnyObject) -> SpecialModelName in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = SpecialModelName()
instance.specialPropertyName = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["$special[property.name]"] as AnyObject?)
return instance
}
// Decoder for [Tag]
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
return Decoders.decode(clazz: [Tag].self, source: source)
}
// Decoder for Tag
Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = Tag()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?)
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?)
return instance
}
// Decoder for [User]
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
return Decoders.decode(clazz: [User].self, source: source)
}
// Decoder for User
Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in
let sourceDictionary = source as! [AnyHashable: Any]
let instance = User()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?)
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"] as AnyObject?)
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"] as AnyObject?)
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"] as AnyObject?)
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"] as AnyObject?)
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"] as AnyObject?)
instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"] as AnyObject?)
instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"] as AnyObject?)
return instance
}
}()
static fileprivate func initialize() {
_ = Decoders.__once
}
}

View File

@ -0,0 +1,25 @@
//
// AdditionalPropertiesClass.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class AdditionalPropertiesClass: JSONEncodable {
public var mapProperty: [String:String]?
public var mapOfMapProperty: [String:[String:String]]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["map_property"] = self.mapProperty?.encodeToJSON()
nillableDictionary["map_of_map_property"] = self.mapOfMapProperty?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,25 @@
//
// Animal.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Animal: JSONEncodable {
public var className: String?
public var color: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["className"] = self.className
nillableDictionary["color"] = self.color
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,11 @@
//
// AnimalFarm.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public typealias AnimalFarm = [Animal]

View File

@ -0,0 +1,27 @@
//
// ApiResponse.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class ApiResponse: JSONEncodable {
public var code: Int32?
public var type: String?
public var message: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["code"] = self.code?.encodeToJSON()
nillableDictionary["type"] = self.type
nillableDictionary["message"] = self.message
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,23 @@
//
// ArrayOfArrayOfNumberOnly.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class ArrayOfArrayOfNumberOnly: JSONEncodable {
public var arrayArrayNumber: [[Double]]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["ArrayArrayNumber"] = self.arrayArrayNumber?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,23 @@
//
// ArrayOfNumberOnly.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class ArrayOfNumberOnly: JSONEncodable {
public var arrayNumber: [Double]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["ArrayNumber"] = self.arrayNumber?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,27 @@
//
// ArrayTest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class ArrayTest: JSONEncodable {
public var arrayOfString: [String]?
public var arrayArrayOfInteger: [[Int64]]?
public var arrayArrayOfModel: [[ReadOnlyFirst]]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["array_of_string"] = self.arrayOfString?.encodeToJSON()
nillableDictionary["array_array_of_integer"] = self.arrayArrayOfInteger?.encodeToJSON()
nillableDictionary["array_array_of_model"] = self.arrayArrayOfModel?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,27 @@
//
// Cat.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Cat: JSONEncodable {
public var className: String?
public var color: String?
public var declawed: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["className"] = self.className
nillableDictionary["color"] = self.color
nillableDictionary["declawed"] = self.declawed
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,25 @@
//
// Category.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Category: JSONEncodable {
public var id: Int64?
public var name: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["name"] = self.name
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,23 @@
//
// Client.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Client: JSONEncodable {
public var client: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["client"] = self.client
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,27 @@
//
// Dog.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class Dog: JSONEncodable {
public var className: String?
public var color: String?
public var breed: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["className"] = self.className
nillableDictionary["color"] = self.color
nillableDictionary["breed"] = self.breed
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,33 @@
//
// EnumArrays.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class EnumArrays: JSONEncodable {
public enum JustSymbol: String {
case greaterThanOrEqualTo = ">="
case dollar = "$"
}
public enum ArrayEnum: String {
case fish = "fish"
case crab = "crab"
}
public var justSymbol: JustSymbol?
public var arrayEnum: [ArrayEnum]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["just_symbol"] = self.justSymbol?.rawValue
nillableDictionary["array_enum"] = self.arrayEnum?.map({$0.rawValue}).encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,17 @@
//
// EnumClass.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public enum EnumClass: String {
case abc = "_abc"
case efg = "-efg"
case xyz = "(xyz)"
func encodeToJSON() -> Any { return self.rawValue }
}

View File

@ -0,0 +1,39 @@
//
// EnumTest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class EnumTest: JSONEncodable {
public enum EnumString: String {
case upper = "UPPER"
case lower = "lower"
}
public enum EnumInteger: Int32 {
case number1 = 1
case numberminus1 = -1
}
public enum EnumNumber: Double {
case number11 = 1.1
case numberminus12 = -1.2
}
public var enumString: EnumString?
public var enumInteger: EnumInteger?
public var enumNumber: EnumNumber?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["enum_string"] = self.enumString?.rawValue
nillableDictionary["enum_integer"] = self.enumInteger?.rawValue
nillableDictionary["enum_number"] = self.enumNumber?.rawValue
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,47 @@
//
// FormatTest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class FormatTest: JSONEncodable {
public var integer: Int32?
public var int32: Int32?
public var int64: Int64?
public var number: Double?
public var float: Float?
public var double: Double?
public var string: String?
public var byte: Data?
public var binary: Data?
public var date: Date?
public var dateTime: Date?
public var uuid: UUID?
public var password: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["integer"] = self.integer?.encodeToJSON()
nillableDictionary["int32"] = self.int32?.encodeToJSON()
nillableDictionary["int64"] = self.int64?.encodeToJSON()
nillableDictionary["number"] = self.number
nillableDictionary["float"] = self.float
nillableDictionary["double"] = self.double
nillableDictionary["string"] = self.string
nillableDictionary["byte"] = self.byte?.encodeToJSON()
nillableDictionary["binary"] = self.binary?.encodeToJSON()
nillableDictionary["date"] = self.date?.encodeToJSON()
nillableDictionary["dateTime"] = self.dateTime?.encodeToJSON()
nillableDictionary["uuid"] = self.uuid?.encodeToJSON()
nillableDictionary["password"] = self.password
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,25 @@
//
// HasOnlyReadOnly.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class HasOnlyReadOnly: JSONEncodable {
public var bar: String?
public var foo: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["bar"] = self.bar
nillableDictionary["foo"] = self.foo
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,23 @@
//
// List.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class List: JSONEncodable {
public var _123List: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["123-list"] = self._123List
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,28 @@
//
// MapTest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class MapTest: JSONEncodable {
public enum MapOfEnumString: String {
case upper = "UPPER"
case lower = "lower"
}
public var mapMapOfString: [String:[String:String]]?
public var mapOfEnumString: [String:String]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["map_map_of_string"] = self.mapMapOfString?.encodeToJSON()//TODO: handle enum map scenario
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,27 @@
//
// MixedPropertiesAndAdditionalPropertiesClass.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class MixedPropertiesAndAdditionalPropertiesClass: JSONEncodable {
public var uuid: UUID?
public var dateTime: Date?
public var map: [String:Animal]?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["uuid"] = self.uuid?.encodeToJSON()
nillableDictionary["dateTime"] = self.dateTime?.encodeToJSON()
nillableDictionary["map"] = self.map?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,26 @@
//
// Model200Response.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Model for testing model name starting with number */
open class Model200Response: JSONEncodable {
public var name: Int32?
public var _class: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["name"] = self.name?.encodeToJSON()
nillableDictionary["class"] = self._class
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,30 @@
//
// Name.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Model for testing model name same as property name */
open class Name: JSONEncodable {
public var name: Int32?
public var snakeCase: Int32?
public var property: String?
public var _123Number: Int32?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["name"] = self.name?.encodeToJSON()
nillableDictionary["snake_case"] = self.snakeCase?.encodeToJSON()
nillableDictionary["property"] = self.property
nillableDictionary["123Number"] = self._123Number?.encodeToJSON()
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -0,0 +1,23 @@
//
// NumberOnly.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class NumberOnly: JSONEncodable {
public var justNumber: Double?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["JustNumber"] = self.justNumber
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

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