[Swift] clean up samples, scripts for deprecated swift generators (#6327)

* decomission swift, swift3

* remove swift batch files, update doc
This commit is contained in:
William Cheng 2020-05-17 14:32:30 +08:00 committed by GitHub
parent b7c8b6e6a5
commit a4e55ea7e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
762 changed files with 1 additions and 104105 deletions

View File

@ -1,5 +0,0 @@
#!/bin/sh
./bin/swift-petstore.sh
./bin/swift-petstore-promisekit.sh
./bin/swift-petstore-rxswift.sh

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "PromiseKit"
}

View File

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

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "RxSwift"
}

View File

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

View File

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

View File

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

View File

@ -1,16 +0,0 @@
#!/bin/sh
echo "#### Petstore Swift API client (default) ####"
./bin/swift3-petstore.sh
echo "#### Petstore Swift API client (promisekit) ####"
./bin/swift3-petstore-promisekit.sh
echo "#### Petstore Swift API client (rxswift) ####"
./bin/swift3-petstore-rxswift.sh
echo "#### Petstore Swift API client (unwraprequired) ####"
./bin/swift3-petstore-unwraprequired.sh
echo "#### Petstore Swift API client (objcCompatible) ####"
./bin/swift3-petstore-objcCompatible.sh

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"objcCompatible": true
}

View File

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

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "PromiseKit"
}

View File

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

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "RxSwift"
}

View File

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

View File

@ -1,7 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"unwrapRequired": true
}

View File

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

View File

@ -1,6 +0,0 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient"
}

View File

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

View File

@ -1,3 +0,0 @@
call .\bin\windows\swift-petstore.bat
call .\bin\windows\swift-petstore-promisekit.bat
call .\bin\windows\swift-petstore-rxswift.bat

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g swift2-deprecated -c bin\swift-petstore-promisekit.json -o samples\client\petstore\swift\promisekit
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g swift2-deprecated -c bin\swift-petstore-rxswift.json -o samples\client\petstore\swift\rxswift
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g swift2-deprecated -o samples\client\petstore\swift\default
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,3 +0,0 @@
call .\bin\windows\swift3-petstore.bat
call .\bin\windows\swift3-petstore-promisekit.bat
call .\bin\windows\swift3-petstore-rxswift.bat

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g swift3-deprecated -c bin\swift3-petstore-promisekit.json -o samples\client\petstore\swift3\promisekit
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g swift3-deprecated -c bin\swift3-petstore-rxswift.json -o samples\client\petstore\swift3\rxswift
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,10 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g swift3-deprecated -o samples\client\petstore\swift3\default
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -57,8 +57,6 @@ The following generators are available:
* [scala-httpclient-deprecated (deprecated)](generators/scala-httpclient-deprecated.md)
* [scala-sttp (beta)](generators/scala-sttp.md)
* [scalaz](generators/scalaz.md)
* [swift2-deprecated (deprecated)](generators/swift2-deprecated.md)
* [swift3-deprecated (deprecated)](generators/swift3-deprecated.md)
* [swift4-deprecated (deprecated)](generators/swift4-deprecated.md)
* [swift5 (beta)](generators/swift5.md)
* [typescript-angular](generators/typescript-angular.md)

View File

@ -1,745 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(Swift3Codegen.class);
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 OBJC_COMPATIBLE = "objcCompatible";
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 = "OpenAPI Generator";
public static final String LENIENT_TYPE_CAST = "lenientTypeCast";
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 = "OpenAPIClient";
protected boolean unwrapRequired;
protected boolean objcCompatible = false;
protected boolean lenientTypeCast = false;
protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "OpenAPIs";
public Swift3Codegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
modifyFeatureSet(features -> features
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON))
.securityFeatures(EnumSet.noneOf(SecurityFeature.class))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
)
);
outputFolder = "generated-code" + File.separator + "swift";
modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift");
embeddedTemplateDir = templateDir = "swift3";
apiPackage = File.separator + "APIs";
modelPackage = File.separator + "Models";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
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(
// name used by swift client
"ErrorResponse", "Response",
// swift keywords
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL",
"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", "Data")
);
typeMapping = new HashMap<>();
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "ISOFullDate");
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");
typeMapping.put("URI", "String");
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(OBJC_COMPATIBLE, "Add additional properties and methods for Objective-C compatibility (default: false)"));
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, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
.defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(LENIENT_TYPE_CAST, "Accept and cast values for simple types (string->bool, string->int, int->string)")
.defaultValue(Boolean.FALSE.toString()));
}
private static CodegenModel reconcileProperties(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// To support inheritance in this generator, we will analyze
// the parent and child models, look for properties that match, and remove
// them from the child models and leave them in the parent.
// Because the child models extend the parents, the properties will be available via the parent.
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
codegenModel.allVars = new ArrayList<CodegenProperty>(codegenProperties);
codegenModel.parentVars = parentCodegenModel.allVars;
// Iterate over all of the parent model properties
boolean removedChildProperty = false;
for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) {
// Now that we have found a prop in the parent class,
// and search the child class for the same prop.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.baseName.equals(parentModelCodegenProperty.baseName)) {
// We found a property in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
removedChildProperty = true;
}
}
}
if (removedChildProperty) {
// If we removed an entry from this model's vars, we need to ensure hasMore is updated
int count = 0, numVars = codegenProperties.size();
for (CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = count < numVars;
}
codegenModel.vars = codegenProperties;
}
return codegenModel;
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "swift3-deprecated";
}
@Override
public String getHelp() {
return "Generates a Swift 3.x client library. IMPORTANT NOTE: this generator (swfit 3.x) is no longer actively maintained so please use 'swift4' generator instead.";
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
final Schema additionalProperties = ModelUtils.getAdditionalProperties(schema);
if (additionalProperties != null) {
codegenModel.additionalPropertiesType = getSchemaType(additionalProperties);
}
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
LOGGER.info("Environment variable SWIFT_POST_PROCESS_FILE not defined so the Swift code may not be properly formatted. To define it, try 'export SWIFT_POST_PROCESS_FILE=/usr/local/bin/swiftformat' (Linux/Mac)");
LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
}
// 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(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
// Setup objcCompatible option, which adds additional properties and methods for Objective-C compatibility
if (additionalProperties.containsKey(OBJC_COMPATIBLE)) {
setObjcCompatible(convertPropertyToBooleanAndWriteBack(OBJC_COMPATIBLE));
}
additionalProperties.put(OBJC_COMPATIBLE, objcCompatible);
// 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)) {
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
}
setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST));
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("Configuration.mustache", sourceFolder, "Configuration.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) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(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(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return "[String:" + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type))
return type;
} else
type = openAPIType;
return toModelName(type);
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("URL");
}
@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(Schema p) {
// nil
return null;
}
@Override
public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) {
return getSchemaType(ModelUtils.getAdditionalProperties(p));
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public String toApiName(String name) {
if (name.length() == 0)
return "DefaultAPI";
return camelize(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;
}
// operationId starts with a number
if (operationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
operationId = camelize(sanitizeName("call_" + operationId), true);
}
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 CodegenModel fromModel(String name, Schema schema) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel codegenModel = super.fromModel(name, schema);
if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
if (allDefinitions != null) {
String parentSchema = codegenModel.parentSchema;
// multilevel inheritance: reconcile properties of all the parents
while (parentSchema != null) {
final Schema parentModel = allDefinitions.get(parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel);
// get the next parent
parentSchema = parentCodegenModel.parentSchema;
}
}
return codegenModel;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public void setUnwrapRequired(boolean unwrapRequired) {
this.unwrapRequired = unwrapRequired;
}
public void setObjcCompatible(boolean objcCompatible) {
this.objcCompatible = objcCompatible;
}
public void setLenientTypeCast(boolean lenientTypeCast) {
this.lenientTypeCast = lenientTypeCast;
}
public void setResponseAs(String[] responseAs) {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@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) {
if (name.length() == 0) {
return "empty";
}
Pattern startWithNumberPattern = Pattern.compile("^\\d+");
Matcher startWithNumberMatcher = startWithNumberPattern.matcher(name);
if (startWithNumberMatcher.find()) {
String startingNumbers = startWithNumberMatcher.group(0);
String nameWithoutStartingNumbers = name.substring(startingNumbers.length());
return "_" + startingNumbers + camelize(nameWithoutStartingNumbers, true);
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)), true);
}
// Camelize only when we have a structure defined below
Boolean camelized = false;
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
name = camelize(name, true);
camelized = true;
}
// Reserved Name
String nameLowercase = StringUtils.lowerCase(name);
if (isReservedWord(nameLowercase)) {
return escapeReservedWord(nameLowercase);
}
// Check for numerical conversions
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;
}
// If we have already camelized the word, don't progress
// any further
if (camelized) {
return name;
}
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 void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
// The default template code has the following logic for assigning a type as Swift Optional:
//
// {{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}
//
// which means:
//
// boolean isSwiftOptional = !unwrapRequired || (unwrapRequired && !property.required);
//
// We can drop the check for unwrapRequired in (unwrapRequired && !property.required)
// due to short-circuit evaluation of the || operator.
boolean isSwiftOptional = !unwrapRequired || !property.required;
boolean isSwiftScalarType = property.isInteger || property.isLong || property.isFloat || property.isDouble || property.isBoolean;
if (isSwiftOptional && isSwiftScalarType) {
// Optional scalar types like Int?, Int64?, Float?, Double?, and Bool?
// do not translate to Objective-C. So we want to flag those
// properties in case we want to put special code in the templates
// which provide Objective-C compatibility.
property.vendorExtensions.put("x-swift-optional-scalar", true);
}
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public void postProcessFile(File file, String fileType) {
if (file == null) {
return;
}
String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
if (StringUtils.isEmpty(swiftPostProcessFile)) {
return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
}
// only process files with swift extension
if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
String command = swiftPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
int exitValue = p.waitFor();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
}

View File

@ -1,657 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
/**
* Swift (2.x) generator is no longer actively maintained. Please use
* 'swift3' or 'swift4' generator instead.
*/
public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(SwiftClientCodegen.class);
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 = "OpenAPI Generator";
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 = "OpenAPIClient";
protected boolean unwrapRequired;
protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "OpenAPIs";
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "swift2-deprecated";
}
@Override
public String getHelp() {
return "Generates a Swift (2.x) client library. IMPORTANT NOTE: this generator (swfit 2.x) is no longer actively maintained so please use 'swift4' generator instead.";
}
public SwiftClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
modifyFeatureSet(features -> features
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON))
.securityFeatures(EnumSet.noneOf(SecurityFeature.class))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
)
);
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";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"Int",
"Int32",
"Int64",
"Float",
"Double",
"Bool",
"Void",
"String",
"Character",
"AnyObject")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"NSData",
"NSDate",
"NSURL", // for file
"NSUUID",
"Array",
"Dictionary",
"Set",
"Any",
"Empty",
"AnyObject")
);
reservedWords = new HashSet<String>(
Arrays.asList(
// name used by swift client
"ErrorResponse",
// swift keywords
// https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html Section: Keywords and Punctuation
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject",
"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", "Data","fileprivate", "open", "rethrows", "defer",
"guard", "repeat", "Any", "catch", "throw", "throws", "try", "indirect", "willSet")
);
typeMapping = new HashMap<String, String>();
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "ISOFullDate");
typeMapping.put("Date", "ISOFullDate");
typeMapping.put("DateTime", "NSDate");
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", "AnyObject");
typeMapping.put("file", "NSURL");
typeMapping.put("binary", "NSURL");
typeMapping.put("ByteArray", "NSData");
typeMapping.put("UUID", "NSUUID");
typeMapping.put("URI", "String");
importMapping = new HashMap<String, String>();
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, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
.defaultValue(Boolean.TRUE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
// 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(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
// 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)) {
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
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) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(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(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return "[String:" + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSchemaType(Schema p) {
String schemaType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type))
return type;
} else
type = schemaType;
return toModelName(type);
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("NSURL");
}
@Override
public boolean isDataTypeBinary(final String dataType) {
return dataType != null && dataType.equals("NSData");
}
/**
* 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(Schema p) {
// nil
return null;
}
@Override
public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(ModelUtils.getAdditionalProperties(p));
return "[String:" + inner + "]";
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty codegenProperty = super.fromProperty(name, p);
// TODO skip array/map of enum for the time being,
// we need to add logic here to handle array/map of enum for any
// dimensions
if (Boolean.TRUE.equals(codegenProperty.isContainer)) {
return codegenProperty;
}
if (codegenProperty.isEnum) {
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values");
for (Object value : values) {
Map<String, String> map = new HashMap<String, String>();
map.put("enum", toSwiftyEnumName(String.valueOf(value)));
map.put("raw", String.valueOf(value));
swiftEnums.add(map);
}
codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum = toEnumName(codegenProperty);
//codegenProperty.datatypeWithEnum =
// StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
// 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(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum";
}
}
return codegenProperty;
}
@SuppressWarnings("static-method")
public String toSwiftyEnumName(String value) {
if (value.length() == 0) {
return "Empty";
}
if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number
value = "Number" + value;
value = value.replaceAll("-", "Minus");
value = value.replaceAll("\\+", "Plus");
value = value.replaceAll("\\.", "Dot");
}
// Prevent from breaking properly cased identifier
if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return value;
}
char[] separators = {'-', '_', ' ', ':', '/'};
return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :/]", "");
}
@Override
public String toApiName(String name) {
if (name.length() == 0)
return "DefaultAPI";
return camelize(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;
}
// operationId starts with a number
if (operationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
operationId = camelize(sanitizeName("call_" + operationId), true);
}
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, List<Server> servers) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// issue 3914 - removed logic designed to remove any parameter of type HeaderParameter
return super.fromOperation(path, httpMethod, operation, servers);
}
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;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
// TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value));
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT));
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name);
// 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

@ -114,8 +114,6 @@ org.openapitools.codegen.languages.SpringCodegen
org.openapitools.codegen.languages.StaticDocCodegen
org.openapitools.codegen.languages.StaticHtmlGenerator
org.openapitools.codegen.languages.StaticHtml2Generator
org.openapitools.codegen.languages.SwiftClientCodegen
org.openapitools.codegen.languages.Swift3Codegen
org.openapitools.codegen.languages.Swift4Codegen
org.openapitools.codegen.languages.Swift5ClientCodegen
org.openapitools.codegen.languages.TypeScriptAngularClientCodegen
@ -127,4 +125,4 @@ org.openapitools.codegen.languages.TypeScriptInversifyClientCodegen
org.openapitools.codegen.languages.TypeScriptJqueryClientCodegen
org.openapitools.codegen.languages.TypeScriptNodeClientCodegen
org.openapitools.codegen.languages.TypeScriptReduxQueryClientCodegen
org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen
org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen

View File

@ -1,50 +0,0 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
class APIHelper {
static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? {
var destination = [String:AnyObject]()
for (key, nillableValue) in source {
if let value: AnyObject = nillableValue {
destination[key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
static func rejectNilHeaders(source: [String:AnyObject?]) -> [String:String] {
var destination = [String:String]()
for (key, nillableValue) in source {
if let value: AnyObject = nillableValue {
destination[key] = "\(value)"
}
}
return destination
}
static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? {
guard let source = source else {
return nil
}
var destination = [String:AnyObject]()
let theTrue = NSNumber(bool: true)
let theFalse = NSNumber(bool: false)
for (key, value) in source {
switch value {
case let x where x === theTrue || x === theFalse:
destination[key] = "\(value as! Bool)"
default:
destination[key] = value
}
}
return destination
}
}

View File

@ -1,77 +0,0 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class {{projectName}}API {
public static var basePath = "{{{basePath}}}"
public static var credential: NSURLCredential?
public static var customHeaders: [String:String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
public class APIBase {
func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? {
let encoded: AnyObject? = encodable?.encodeToJSON()
if encoded! is [AnyObject] {
var dictionary = [String:AnyObject]()
for (index, item) in (encoded as! [AnyObject]).enumerate() {
dictionary["\(index)"] = item
}
return dictionary
} else {
return encoded as? [String:AnyObject]
}
}
}
public class RequestBuilder<T> {
var credential: NSURLCredential?
var headers: [String:String]
let parameters: [String:AnyObject]?
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: ((NSProgress) -> ())?
required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
self.headers = headers
addHeaders({{projectName}}API.customHeaders)
}
public func addHeaders(aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
public func addHeader(name name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
public func addCredential() -> Self {
self.credential = {{projectName}}API.credential
return self
}
}
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -1,207 +0,0 @@
// AlamofireImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
}
public struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]()
private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT)
public subscript(key: K) -> V? {
get {
var value: V?
dispatch_sync(queue) {
value = self.dictionary[key]
}
return value
}
set {
dispatch_barrier_sync(queue) {
self.dictionary[key] = newValue
}
}
}
}
// Store manager to retain its reference
private var managerStore = SynchronizedDictionary<String, Alamofire.Manager>()
class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool, headers: [String : String] = [:]) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers)
}
override func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) {
let managerId = NSUUID().UUIDString
// Create a new manager for each request to customize its request header
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = buildHeaders()
let manager = Alamofire.Manager(configuration: configuration)
managerStore[managerId] = manager
let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL
let xMethod = Alamofire.Method(rawValue: method)
let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(
xMethod!, URLString, headers: nil,
multipartFormData: { mpForm in
for (k, v) in self.parameters! {
switch v {
case let fileURL as NSURL:
mpForm.appendBodyPart(fileURL: fileURL, name: k)
case let string as NSString:
mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
case let number as NSNumber:
mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
default:
fatalError("Unprocessable value \(v) with key \(k)")
}
}
},
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let uploadRequest, _, _):
if let onProgressReady = self.onProgressReady {
onProgressReady(uploadRequest.progress)
}
self.processRequest(uploadRequest, managerId, completion)
case .Failure(let encodingError):
completion(response: nil, error: ErrorResponse.error(415, nil, encodingError))
}
}
)
} else {
let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request, managerId, completion)
}
}
private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response<T>?, error: ErrorType?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
managerStore[managerId] = nil
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
response: Response(
response: stringResponse.response!,
body: (stringResponse.result.value ?? "") as! T
),
error: nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
response: Response(
response: voidResponse.response!,
body: nil
),
error: nil
)
})
case is NSData.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if dataResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
response: Response(
response: dataResponse.response!,
body: dataResponse.data as! T
),
error: nil
)
})
default:
validatedRequest.responseJSON(options: .AllowFragments) { response in
cleanupRequest()
if response.result.isFailure {
completion(response: nil, error: ErrorResponse.error(response.response?.statusCode ?? 500, response.data, response.result.error!))
return
}
if () is T {
completion(response: Response(response: response.response!, body: () as! T), error: nil)
return
}
if let json: AnyObject = response.result.value {
let body = Decoders.decode(clazz: T.self, source: json)
completion(response: Response(response: response.response!, body: body), error: nil)
return
} else if "" is T {
completion(response: Response(response: response.response!, body: "" as! T), error: nil)
return
}
completion(response: nil, error: ErrorResponse.error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
}
}
}
private func buildHeaders() -> [String: AnyObject] {
var httpHeaders = Manager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
}

View File

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

View File

@ -1,192 +0,0 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}
extension Bool: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Float: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Int: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> AnyObject { return NSNumber(int: self) }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) }
}
extension Double: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension String: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
private func encodeIfPossible<T>(object: T) -> AnyObject {
if object is JSONEncodable {
return (object as! JSONEncodable).encodeToJSON()
} else {
return object as! AnyObject
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.map(encodeIfPossible)
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> AnyObject {
var dictionary = [NSObject:AnyObject]()
for (key, value) in self {
dictionary[key as! NSObject] = encodeIfPossible(value)
}
return dictionary
}
}
extension NSData: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
}
}
private let dateFormatter: NSDateFormatter = {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return fmt
}()
extension NSDate: JSONEncodable {
func encodeToJSON() -> AnyObject {
return dateFormatter.stringFromDate(self)
}
}
extension NSUUID: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.UUIDString
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}
{{#usePromiseKit}}extension RequestBuilder {
public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pendingPromise()
self.execute { (response: Response<T>?, error: ErrorType?) in
if let response = response {
deferred.fulfill(response)
} else {
deferred.reject(error!)
}
}
return deferred.promise
}
}{{/usePromiseKit}}

View File

@ -1,182 +0,0 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> AnyObject
}
public enum ErrorResponse : ErrorType {
case Error(Int, NSData?, ErrorType)
}
public class Response<T> {
public let statusCode: Int
public let header: [String: String]
public 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: NSHTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String:String]()
for case let (key, value) as (String, String) in rawHeader {
header[key] = value
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
private var once = dispatch_once_t()
class Decoders {
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
let key = "\(T.self)"
decoders[key] = { decoder($0) as! AnyObject }
}
static func decode<T>(clazz 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 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 clazz: T.Type, source: AnyObject) -> T {
initialize()
if T.self is Int32.Type && source is NSNumber {
return source.intValue as! T;
}
if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T;
}
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
}
if source is T {
return source as! T
}
if T.self is NSData.Type && source is String {
return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) 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 OpenAPI spec file is insufficient")
}
}
static func decodeOptional<T>(clazz 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 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 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)
}
}
static private func initialize() {
dispatch_once(&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) -> NSDateFormatter in
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
formatter.dateFormat = format
return formatter
}
// Decoder for NSDate
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.dateFromString(sourceString) {
return date
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
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
let sourceDictionary = source as! [NSObject:AnyObject]
{{#unwrapRequired}}
let instance = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{#isEnum}}{{name}}: {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "")! {{/isEnum}}{{^isEnum}}{{name}}: Decoders.decode(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]!){{/isEnum}}{{/requiredVars}})
{{#optionalVars}}
{{#isEnum}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "")
{{/isEnum}}
{{^isEnum}}
instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"])
{{/isEnum}}
{{/optionalVars}}
{{/unwrapRequired}}
{{^unwrapRequired}}
let instance = {{classname}}(){{#vars}}{{#isEnum}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "") {{/isEnum}}{{^isEnum}}
instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]){{/isEnum}}{{/vars}}
{{/unwrapRequired}}
return instance
}{{/model}}
{{/models}}
}
}
}

View File

@ -1,37 +0,0 @@
Pod::Spec.new do |s|
s.name = '{{projectName}}'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}'
s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:openapitools/openapi-generator.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}}'Proprietary'{{/podLicense}}
s.homepage = '{{podHomepage}}{{^podHomepage}}https://openapi-generator.tech{{/podHomepage}}'
s.summary = '{{podSummary}}{{^podSummary}}{{projectName}} Swift SDK{{/podSummary}}'
{{#podDescription}}
s.description = '{{podDescription}}'
{{/podDescription}}
{{#podScreenshots}}
s.screenshots = {{& podScreenshots}}
{{/podScreenshots}}
{{#podDocumentationURL}}
s.documentation_url = '{{podDocumentationURL}}'
{{/podDocumentationURL}}
s.source_files = '{{projectName}}/Classes/**/*.swift'
{{#usePromiseKit}}
s.dependency 'PromiseKit', '~> 3.5.3'
{{/usePromiseKit}}
{{#useRxSwift}}
s.dependency 'RxSwift', '~> 2.6.1'
{{/useRxSwift}}
s.dependency 'Alamofire', '~> 3.5.1'
end

View File

@ -1 +0,0 @@
"{{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

@ -1,148 +0,0 @@
{{#operations}}//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
import RxSwift{{/useRxSwift}}
{{#swiftUseApiNamespace}}
extension {{projectName}}API {
{{/swiftUseApiNamespace}}
{{#description}}
/** {{description}} */{{/description}}
public class {{classname}}: APIBase {
{{#operation}}
{{#allParams}}
{{#isEnum}}
{{^isContainer}}
/**
* enum for parameter {{paramName}}
*/
public enum {{{datatypeWithEnum}}}_{{operationId}}: String { {{#allowableValues}}{{#values}}
case {{enum}} = "{{raw}}"{{/values}}{{/allowableValues}}
}
{{/isContainer}}
{{/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
*/
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in
completion({{#returnType}}data: response?.body, {{/returnType}}error: 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}}>
*/
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{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}}>.pendingPromise()
{{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}}>
*/
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{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 ErrorType))
} 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}}
{{#hasResponseHeaders}}
- responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}]
{{/hasResponseHeaders}}
{{#examples}}
- examples: {{{examples}}}
{{/examples}}
{{#externalDocs}}
- externalDocs: {{externalDocs}}
{{/externalDocs}}
{{#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}}
*/
public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{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.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", withString: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .LiteralSearch, range: nil){{/pathParams}}
let URLString = {{projectName}}API.basePath + path
{{#bodyParam}}
let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}}
let nillableParameters: [String:AnyObject?] = {{^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){{#headerParams}}{{^secondaryParam}}
let nillableHeaders: [String: AnyObject?] = [{{/secondaryParam}}
{{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]
let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders){{/hasMore}}{{/headerParams}}
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}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}{{#headerParams}}{{^secondaryParam}}, headers: headerParameters{{/secondaryParam}}{{/headerParams}})
}
{{/operation}}
}
{{#swiftUseApiNamespace}}
}
{{/swiftUseApiNamespace}}
{{/operations}}

View File

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

View File

@ -1,63 +0,0 @@
# 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

@ -1,56 +0,0 @@
{{#models}}{{#model}}//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#description}}
/** {{description}} */{{/description}}
public class {{classname}}: JSONEncodable {
{{#vars}}
{{#isEnum}}
public enum {{datatypeWithEnum}}: String { {{#allowableValues}}{{#values}}
case {{enum}} = "{{raw}}"{{/values}}{{/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() -> AnyObject {
var nillableDictionary = [String:AnyObject?](){{#vars}}{{^isContainer}}{{#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}}{{/isContainer}}{{#isContainer}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isContainer}}{{/vars}}
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}{{/model}}
{{/models}}

View File

@ -1,75 +0,0 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
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 rejectNilHeaders(_ source: [String:Any?]) -> [String:String] {
var destination = [String:String]()
for (key, nillableValue) in source {
if let value: Any = nillableValue {
destination[key] = "\(value)"
}
}
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
}
static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? {
let returnValues = values
.filter { $0.1 != nil }
.map { (item: (_key: String, _value: Any?)) -> [URLQueryItem] in
if let value = item._value as? Array<String> {
return value.map { (v) -> URLQueryItem in
URLQueryItem(
name: item._key,
value: v
)
}
} else {
return [URLQueryItem(
name: item._key,
value: "\(item._value!)"
)]
}
}
.flatMap { $0 }
if returnValues.isEmpty { return nil }
return returnValues
}
}

View File

@ -1,77 +0,0 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class {{projectName}}API {
open static var basePath = "{{{basePath}}}"
open static var credential: URLCredential?
open static var customHeaders: [String:String] = [:]
open 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]
public let parameters: Any?
public let isBody: Bool
public let method: String
public let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((Progress) -> ())?
required public init(method: String, URLString: String, parameters: Any?, isBody: Bool, headers: [String:String] = [:]) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
self.headers = headers
addHeaders({{projectName}}API.customHeaders)
}
open func addHeaders(_ aHeaders:[String:String]) {
for (header, value) in aHeaders {
addHeader(name: header, value: value)
}
}
open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: ErrorResponse?) -> Void) { }
@discardableResult 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

@ -1,374 +0,0 @@
// AlamofireImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
}
private struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]()
private let queue = DispatchQueue(
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
public subscript(key: K) -> V? {
get {
var value: V?
queue.sync {
value = self.dictionary[key]
}
return value
}
set {
queue.sync(flags: DispatchWorkItemFlags.barrier) {
self.dictionary[key] = newValue
}
}
}
}
class JSONEncodingWrapper: ParameterEncoding {
var bodyParameters: Any?
var encoding: JSONEncoding = JSONEncoding()
public init(parameters: Any?) {
self.bodyParameters = parameters
}
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
return try encoding.encode(urlRequest, withJSONObject: bodyParameters)
}
}
// Store manager to retain its reference
private var managerStore = SynchronizedDictionary<String, Alamofire.SessionManager>()
open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required public init(method: String, URLString: String, parameters: Any?, isBody: Bool, headers: [String : String] = [:]) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers)
}
/**
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)
}
/**
May be overridden by a subclass if you want to control the Content-Type
that is given to an uploaded form part.
Return nil to use the default behavior (inferring the Content-Type from
the file extension). Return the desired Content-Type otherwise.
*/
open func contentTypeForFormPart(fileURL: URL) -> String? {
return nil
}
/**
May be overridden by a subclass if you want to control the request
configuration (e.g. to override the cache policy).
*/
open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest {
return manager.request(URLString, method: method, parameters: parameters as? Parameters, encoding: encoding, headers: headers)
}
override open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: ErrorResponse?) -> 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 ? JSONEncodingWrapper(parameters: parameters) : URLEncoding()
let xMethod = Alamofire.HTTPMethod(rawValue: method)
let param = parameters as? Parameters
let fileKeys = param == nil ? [] : param!.filter { $1 is NSURL }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(multipartFormData: { mpForm in
for (k, v) in param! {
switch v {
case let fileURL as URL:
if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) {
mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType)
}
else {
mpForm.append(fileURL, withName: k)
}
case let string as String:
mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k)
case let number as NSNumber:
mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k)
default:
fatalError("Unprocessable value \(v) with key \(k)")
}
}
}, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
if let onProgressReady = self.onProgressReady {
onProgressReady(upload.uploadProgress)
}
self.processRequest(request: upload, managerId, completion)
case .failure(let encodingError):
completion(nil, ErrorResponse.HttpError(statusCode: 415, data: nil, error: encodingError))
}
})
} else {
let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers)
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: ErrorResponse?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
managerStore[managerId] = nil
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.HttpError(statusCode: stringResponse.response?.statusCode ?? 500, data: stringResponse.data, error: stringResponse.result.error as 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.HttpError(statusCode: voidResponse.response?.statusCode ?? 500, data: voidResponse.data, error: 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.HttpError(statusCode: dataResponse.response?.statusCode ?? 500, data: dataResponse.data, error: dataResponse.result.error!)
)
return
}
completion(
Response(
response: dataResponse.response!,
body: (dataResponse.data as! T)
),
nil
)
})
case is URL.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
do {
guard !dataResponse.result.isFailure else {
throw DownloadException.responseFailed
}
guard let data = dataResponse.data else {
throw DownloadException.responseDataMissing
}
guard let request = request.request else {
throw DownloadException.requestMissing
}
let fileManager = FileManager.default
let urlRequest = try request.asURLRequest()
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let requestURL = try self.getURL(from: urlRequest)
var requestPath = try self.getPath(from: requestURL)
if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) {
requestPath = requestPath.appending("/\(headerFileName)")
}
let filePath = documentsDirectory.appendingPathComponent(requestPath)
let directoryPath = filePath.deletingLastPathComponent().path
try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
try data.write(to: filePath, options: .atomic)
completion(
Response(
response: dataResponse.response!,
body: (filePath as! T)
),
nil
)
} catch let requestParserError as DownloadException {
completion(nil, ErrorResponse.HttpError(statusCode: 400, data: dataResponse.data, error: requestParserError))
} catch let error {
completion(nil, ErrorResponse.HttpError(statusCode: 400, data: dataResponse.data, error: error))
}
return
})
default:
validatedRequest.responseJSON(options: .allowFragments) { response in
cleanupRequest()
if response.result.isFailure {
completion(nil, ErrorResponse.HttpError(statusCode: response.response?.statusCode ?? 500, data: response.data, error: response.result.error!))
return
}
// handle HTTP 204 No Content
// NSNull would crash decoders
if response.response?.statusCode == 204 && response.result.value is NSNull{
completion(nil, nil)
return
}
if () is T {
completion(Response(response: response.response!, body: (() as! T)), nil)
return
}
if let json: Any = response.result.value {
let decoded = Decoders.decode(clazz: T.self, source: json as AnyObject, instance: nil)
switch decoded {
case let .success(object): completion(Response(response: response.response!, body: object), nil)
case let .failure(error): completion(nil, ErrorResponse.DecodeError(response: response.data, decodeError: error))
}
return
} else if "" is T {
completion(Response(response: response.response!, body: ("" as! T)), nil)
return
}
completion(nil, ErrorResponse.HttpError(statusCode: 500, data: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
}
}
}
open func buildHeaders() -> [String: String] {
var httpHeaders = SessionManager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? {
guard let contentDisposition = contentDisposition else {
return nil
}
let items = contentDisposition.components(separatedBy: ";")
var filename : String? = nil
for contentItem in items {
let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else {
break
}
filename = contentItem
return filename?
.replacingCharacters(in: range, with:"")
.replacingOccurrences(of: "\"", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
return filename
}
fileprivate func getPath(from url : URL) throws -> String {
guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else {
throw DownloadException.requestMissingPath
}
if path.hasPrefix("/") {
path.remove(at: path.startIndex)
}
return path
}
fileprivate func getURL(from urlRequest : URLRequest) throws -> URL {
guard let url = urlRequest.url else {
throw DownloadException.requestMissingURL
}
return url
}
}
fileprivate enum DownloadException : Error {
case responseDataMissing
case responseFailed
case requestMissing
case requestMissingPath
case requestMissingURL
}

View File

@ -1,3 +0,0 @@
github "Alamofire/Alamofire" ~> 4.5{{#usePromiseKit}}
github "mxcl/PromiseKit" ~> 4.4{{/usePromiseKit}}{{#useRxSwift}}
github "ReactiveX/RxSwift" "rxswift-3.0"{{/useRxSwift}}

View File

@ -1,15 +0,0 @@
// Configuration.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class Configuration {
// This value is used to configure the date formatter that is used to serialize dates into JSON format.
// You must set it prior to encoding any dates, and it will only be read once.
open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
}

View File

@ -1,200 +0,0 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
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] = 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 = Configuration.dateFormat
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
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts a Date to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date: Date) -> ISOFullDate? {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(
[
.year,
.month,
.day,
],
from: date
)
guard
let year = components.year,
let month = components.month,
let day = components.day
else {
return nil
}
return ISOFullDate(
year: year,
month: month,
day: day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string: String) -> ISOFullDate? {
let components = string
.characters
.split(separator: "-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to a Date, in the default time zone.
- returns: A Date from the components of the receiver, in the default time zone.
*/
public func toDate() -> Date? {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = TimeZone.ReferenceType.default
let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> Any {
return "\(year)-\(month)-\(day)"
}
}
{{#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

@ -1,402 +0,0 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> Any
}
public enum ErrorResponse : Error {
case HttpError(statusCode: Int, data: Data?, error: Error)
case DecodeError(response: Data?, decodeError: DecodeError)
}
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 case let (key, value) as (String, String) in rawHeader {
header[key] = value
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
public enum Decoded<ValueType> {
case success(ValueType)
case failure(DecodeError)
}
public extension Decoded {
var value: ValueType? {
switch self {
case let .success(value):
return value
case .failure:
return nil
}
}
}
public enum DecodeError {
case typeMismatch(expected: String, actual: String)
case missingKey(key: String)
case parseError(message: String)
}
private var once = Int()
class Decoders {
static fileprivate var decoders = Dictionary<String, ((AnyObject, AnyObject?) -> AnyObject)>()
static func addDecoder<T>(clazz: T.Type, decoder: @escaping ((AnyObject, AnyObject?) -> Decoded<T>)) {
let key = "\(T.self)"
decoders[key] = { decoder($0, $1) as AnyObject }
}
static func decode<T>(clazz: T.Type, discriminator: String, source: AnyObject) -> Decoded<T> {
let key = discriminator
if let decoder = decoders[key], let value = decoder(source, nil) as? Decoded<T> {
return value
} else {
return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source)))
}
}
static func decode<T>(clazz: [T].Type, source: AnyObject) -> Decoded<[T]> {
if let sourceArray = source as? [AnyObject] {
var values = [T]()
for sourceValue in sourceArray {
switch Decoders.decode(clazz: T.self, source: sourceValue, instance: nil) {
case let .success(value):
values.append(value)
case let .failure(error):
return .failure(error)
}
}
return .success(values)
} else {
return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source)))
}
}
static func decode<T>(clazz: T.Type, source: AnyObject) -> Decoded<T> {
switch Decoders.decode(clazz: T.self, source: source, instance: nil) {
case let .success(value):
return .success(value)
case let .failure(error):
return .failure(error)
}
}
static open func decode<T: RawRepresentable>(clazz: T.Type, source: AnyObject) -> Decoded<T> {
if let value = source as? T.RawValue {
if let enumValue = T.init(rawValue: value) {
return .success(enumValue)
} else {
return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)"))
}
} else {
return .failure(.typeMismatch(expected: "\(T.RawValue.self) matching a case from the enumeration \(T.self)", actual: String(describing: type(of: source))))
}
}
static func decode<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject) -> Decoded<[Key:T]> {
if let sourceDictionary = source as? [Key: AnyObject] {
var dictionary = [Key:T]()
for (key, value) in sourceDictionary {
switch Decoders.decode(clazz: T.self, source: value, instance: nil) {
case let .success(value):
dictionary[key] = value
case let .failure(error):
return .failure(error)
}
}
return .success(dictionary)
} else {
return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source)))
}
}
static func decodeOptional<T: RawRepresentable>(clazz: T.Type, source: AnyObject?) -> Decoded<T?> {
guard !(source is NSNull), source != nil else { return .success(nil) }
if let value = source as? T.RawValue {
if let enumValue = T.init(rawValue: value) {
return .success(enumValue)
} else {
return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)"))
}
} else {
return .failure(.typeMismatch(expected: "\(T.RawValue.self) matching a case from the enumeration \(T.self)", actual: String(describing: type(of: source))))
}
}
static func decode<T>(clazz: T.Type, source: AnyObject, instance: AnyObject?) -> Decoded<T> {
initialize()
if let sourceNumber = source as? NSNumber, let value = sourceNumber.int32Value as? T, T.self is Int32.Type {
return .success(value)
}
if let sourceNumber = source as? NSNumber, let value = sourceNumber.int32Value as? T, T.self is Int64.Type {
return .success(value)
}
if let intermediate = source as? String, let value = UUID(uuidString: intermediate) as? T, source is String, T.self is UUID.Type {
return .success(value)
}
if let value = source as? T {
return .success(value)
}
if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T {
return .success(value)
}
{{#lenientTypeCast}}
if T.self is Int32.Type && source is String {
return (source as! NSString).intValue as! T
}
if T.self is Int64.Type && source is String {
return (source as! NSString).intValue as! T
}
if T.self is Bool.Type && source is String {
return (source as! NSString).boolValue as! T
}
if T.self is String.Type && source is NSNumber {
return String(describing: source) as! T
}
{{/lenientTypeCast}}
let key = "\(T.self)"
if let decoder = decoders[key], let value = decoder(source, instance) as? Decoded<T> {
return value
} else {
return .failure(.typeMismatch(expected: String(describing: clazz), actual: String(describing: source)))
}
}
//Convert a Decoded so that its value is optional. DO WE STILL NEED THIS?
static func toOptional<T>(decoded: Decoded<T>) -> Decoded<T?> {
return .success(decoded.value)
}
static func decodeOptional<T>(clazz: T.Type, source: AnyObject?) -> Decoded<T?> {
if let source = source, !(source is NSNull) {
switch Decoders.decode(clazz: clazz, source: source, instance: nil) {
case let .success(value): return .success(value)
case let .failure(error): return .failure(error)
}
} else {
return .success(nil)
}
}
static func decodeOptional<T>(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> where T: RawRepresentable {
if let source = source as? [AnyObject] {
var values = [T]()
for sourceValue in source {
switch Decoders.decodeOptional(clazz: T.self, source: sourceValue) {
case let .success(value): if let value = value { values.append(value) }
case let .failure(error): return .failure(error)
}
}
return .success(values)
} else {
return .success(nil)
}
}
static func decodeOptional<T>(clazz: [T].Type, source: AnyObject?) -> Decoded<[T]?> {
if let source = source as? [AnyObject] {
var values = [T]()
for sourceValue in source {
switch Decoders.decode(clazz: T.self, source: sourceValue, instance: nil) {
case let .success(value): values.append(value)
case let .failure(error): return .failure(error)
}
}
return .success(values)
} else {
return .success(nil)
}
}
static func decodeOptional<T, Key: Hashable>(clazz: [Key:T].Type, source: AnyObject?) -> Decoded<[Key:T]?> {
if let sourceDictionary = source as? [Key: AnyObject] {
var dictionary = [Key:T]()
for (key, value) in sourceDictionary {
switch Decoders.decode(clazz: T.self, source: value, instance: nil) {
case let .success(value): dictionary[key] = value
case let .failure(error): return .failure(error)
}
}
return .success(dictionary)
} else {
return .success(nil)
}
}
static func decodeOptional<T: RawRepresentable, U: AnyObject>(clazz: T, source: AnyObject) -> Decoded<T?> where T.RawValue == U {
if let value = source as? U {
if let enumValue = T.init(rawValue: value) {
return .success(enumValue)
} else {
return .failure(.typeMismatch(expected: "A value from the enumeration \(T.self)", actual: "\(value)"))
}
} else {
return .failure(.typeMismatch(expected: "String", actual: String(describing: type(of: source))))
}
}
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",
"yyyy-MM-dd HH:mm:ss"
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = format
return formatter
}
// Decoder for Date
Decoders.addDecoder(clazz: Date.self) { (source: AnyObject, instance: AnyObject?) -> Decoded<Date> in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.date(from: sourceString) {
return .success(date)
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return .success(Date(timeIntervalSince1970: Double(sourceInt / 1000) ))
}
if source is String || source is Int {
return .failure(.parseError(message: "Could not decode date"))
} else {
return .failure(.typeMismatch(expected: "String or Int", actual: "\(source)"))
}
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self) { (source: AnyObject, instance: AnyObject?) -> Decoded<ISOFullDate> in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return .success(isoDate)
} else {
return .failure(.typeMismatch(expected: "ISO date", actual: "\(source)"))
}
}
{{#models}}
{{#model}}
{{^isArrayModel}}
// Decoder for [{{{classname}}}]
Decoders.addDecoder(clazz: [{{{classname}}}].self) { (source: AnyObject, instance: AnyObject?) -> Decoded<[{{{classname}}}]> in
return Decoders.decode(clazz: [{{{classname}}}].self, source: source)
}
// Decoder for {{{classname}}}
Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject, instance: AnyObject?) -> Decoded<{{{classname}}}> in
{{#isEnum}}
//TODO: I don't think we need this anymore
return Decoders.decode(clazz: {{{classname}}}.self, source: source, instance: instance)
{{/isEnum}}
{{^isEnum}}
{{#allVars.isEmpty}}
if let source = source as? {{classname}} {
return .success(source)
} else {
return .failure(.typeMismatch(expected: "Typealias {{classname}}", actual: "\(source)"))
}
{{/allVars.isEmpty}}
{{^allVars.isEmpty}}
if let sourceDictionary = source as? [AnyHashable: Any] {
{{#discriminator}}
// Check discriminator to support inheritance
if let discriminator = sourceDictionary["{{{discriminatorName}}}"] as? String, instance == nil && discriminator != "{{classname}}"{
return Decoders.decode(clazz: {{classname}}.self, discriminator: discriminator, source: source)
}
{{/discriminator}}
{{#additionalPropertiesType}}
var propsDictionary = sourceDictionary
let keys : [AnyHashable] = [{{#allVars}}{{^-last}}"{{baseName}}", {{/-last}}{{#-last}}"{{baseName}}"{{/-last}}{{/allVars}}]
{{/additionalPropertiesType}}
{{#unwrapRequired}}
{{#requiredVars}}
guard let {{name}}Source = sourceDictionary["{{baseName}}"] as AnyObject? else {
return .failure(.missingKey(key: "{{baseName}}"))
}
guard let {{name}} = Decoders.decode(clazz: {{#isEnum}}{{^isListContainer}}{{classname}}.{{enumName}}.self{{/isListContainer}}{{#isListContainer}}Array<{{classname}}.{{enumName}}>.self{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}.self{{/isEnum}}.self, source: {{name}}Source).value else {
return .failure(.typeMismatch(expected: "{{classname}}", actual: "\({{name}}Source)"))
}
{{/requiredVars}}
let _result = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{name}}: {{name}}{{/requiredVars}})
{{#optionalVars}}
switch Decoders.decodeOptional(clazz: {{#isEnum}}{{^isListContainer}}{{classname}}.{{enumName}}.self{{/isListContainer}}{{#isListContainer}}Array<{{classname}}.{{enumName}}>.self{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}.self{{/isEnum}}, source: sourceDictionary["{{baseName}}"] as AnyObject?) {
case let .success(value): _result.{{name}} = value
case let .failure(error): break
}
{{/optionalVars}}
{{/unwrapRequired}}
{{^unwrapRequired}}
let _result = instance == nil ? {{classname}}() : instance as! {{classname}}
{{#parent}}
if decoders["\({{parent}}.self)"] != nil {
_ = Decoders.decode(clazz: {{parent}}.self, source: source, instance: _result)
}
{{/parent}}
{{#allVars}}
switch Decoders.decodeOptional(clazz: {{#isEnum}}{{^isListContainer}}{{classname}}.{{enumName}}.self{{/isListContainer}}{{#isListContainer}}Array<{{classname}}.{{enumName}}>.self{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}.self{{/isEnum}}, source: sourceDictionary["{{baseName}}"] as AnyObject?) {
{{#isEnum}}{{#isMapContainer}}/*{{/isMapContainer}}{{/isEnum}}
case let .success(value): _result.{{name}} = value
case let .failure(error): break
{{#isEnum}}{{#isMapContainer}}*/ default: break //TODO: handle enum map scenario{{/isMapContainer}}{{/isEnum}}
}
{{/allVars}}
{{/unwrapRequired}}
{{#additionalPropertiesType}}
for key in keys {
propsDictionary.removeValue(forKey: key)
}
for key in propsDictionary.keys {
switch Decoders.decodeOptional(clazz: String.self, source: propsDictionary[key] as AnyObject?) {
case let .success(value): _result[key] = value
default: continue
}
}
{{/additionalPropertiesType}}
return .success(_result)
} else {
return .failure(.typeMismatch(expected: "{{classname}}", actual: "\(source)"))
}
{{/allVars.isEmpty}}
{{/isEnum}}
}
{{/isArrayModel}}
{{/model}}
{{/models}}
}()
static fileprivate func initialize() {
_ = Decoders.__once
}
}

View File

@ -1,38 +0,0 @@
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.tvos.deployment_target = '9.0'
s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}'
s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:OpenAPITools/openapi-generator.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}}'Proprietary'{{/podLicense}}
s.homepage = '{{podHomepage}}{{^podHomepage}}https://github.com/OpenAPITools/openapi-generator{{/podHomepage}}'
s.summary = '{{podSummary}}{{^podSummary}}{{projectName}} Swift SDK{{/podSummary}}'
{{#podDescription}}
s.description = '{{podDescription}}'
{{/podDescription}}
{{#podScreenshots}}
s.screenshots = {{& podScreenshots}}
{{/podScreenshots}}
{{#podDocumentationURL}}
s.documentation_url = '{{podDocumentationURL}}'
{{/podDocumentationURL}}
s.source_files = '{{projectName}}/Classes/**/*.swift'
{{#usePromiseKit}}
s.dependency 'PromiseKit/CorePromise', '~> 4.4.0'
{{/usePromiseKit}}
{{#useRxSwift}}
s.dependency 'RxSwift', '3.6.1'
{{/useRxSwift}}
s.dependency 'Alamofire', '~> 4.5.0'
end

View File

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

View File

@ -1,177 +0,0 @@
{{#operations}}//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
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: ErrorResponse?) -> 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 Disposables.create()
}
}
{{/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}}
{{#hasResponseHeaders}}
- responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}]
{{/hasResponseHeaders}}
{{#externalDocs}}
- externalDocs: {{externalDocs}}
{{/externalDocs}}
{{#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}}
let {{paramName}}PreEscape = "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})"
let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}}
let URLString = {{projectName}}API.basePath + path
{{#bodyParam}}
let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON()
{{/bodyParam}}
{{^bodyParam}}
{{#hasFormParams}}
let formParams: [String:Any?] = [
{{#formParams}}
{{> _param}}{{#hasMore}},{{/hasMore}}
{{/formParams}}
]
let nonNullParameters = APIHelper.rejectNil(formParams)
let parameters = APIHelper.convertBoolToString(nonNullParameters)
{{/hasFormParams}}
{{^hasFormParams}}
let parameters: [String:Any]? = nil
{{/hasFormParams}}
{{/bodyParam}}{{#hasQueryParams}}
var url = URLComponents(string: URLString)
url?.queryItems = APIHelper.mapValuesToQueryItems(values:[
{{#queryParams}}
{{> _param}}{{#hasMore}},{{/hasMore}}
{{/queryParams}}
]){{/hasQueryParams}}{{^hasQueryParams}}
let url = URLComponents(string: URLString){{/hasQueryParams}}
{{#headerParams}}
{{^secondaryParam}}
let nillableHeaders: [String: Any?] = [
{{/secondaryParam}}
{{> _param}}{{#hasMore}},{{/hasMore}}
{{^hasMore}}
]
let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders)
{{/hasMore}}
{{/headerParams}}
let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, isBody: {{hasBodyParam}}{{#headerParams}}{{^secondaryParam}}, headers: headerParameters{{/secondaryParam}}{{/headerParams}})
}
{{/operation}}
}
{{#swiftUseApiNamespace}}
}
{{/swiftUseApiNamespace}}
{{/operations}}

View File

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

View File

@ -1,63 +0,0 @@
# 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

@ -1,105 +0,0 @@
{{#models}}
{{#model}}
//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
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}}
open class {{classname}}: {{#parent}}{{{parent}}}{{/parent}}{{^parent}}JSONEncodable{{/parent}} {
{{#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}}{{#objcCompatible}}{{#vendorExtensions.x-swift-optional-scalar}}
public var {{name}}Num: NSNumber? {
get {
return {{name}}.map({ return NSNumber(value: $0) })
}
}{{/vendorExtensions.x-swift-optional-scalar}}{{/objcCompatible}}
{{/isEnum}}
{{/vars}}
{{#additionalPropertiesType}}
public var additionalProperties: [AnyHashable:{{{additionalPropertiesType}}}] = [:]
{{/additionalPropertiesType}}
{{^unwrapRequired}}
{{^parent}}public init() {}{{/parent}}{{/unwrapRequired}}
{{#unwrapRequired}}
public init({{#allVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{dataType}}{{/isEnum}}{{^required}}?=nil{{/required}}{{/allVars}}) {
{{#vars}}
self.{{name}} = {{name}}
{{/vars}}
}{{/unwrapRequired}}
{{#additionalPropertiesType}}
public subscript(key: AnyHashable) -> {{{additionalPropertiesType}}}? {
get {
if let value = additionalProperties[key] {
return value
}
return nil
}
set {
additionalProperties[key] = newValue
}
}
{{/additionalPropertiesType}}
// MARK: JSONEncodable
{{#parent}}override {{/parent}}open func encodeToJSON() -> Any {
var nillableDictionary = {{#parent}}super.encodeToJSON() as? [String:Any?] ?? {{/parent}}[String:Any?](){{#vars}}{{^isContainer}}{{#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}}{{/isContainer}}{{#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}}
{{#additionalPropertiesType}}
for (key, value) in additionalProperties {
if let key = key as? String {
nillableDictionary[key] = value
}
}
{{/additionalPropertiesType}}
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
{{/isEnum}}
{{/isArrayModel}}
{{/model}}
{{/models}}

View File

@ -1,90 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.options;
import com.google.common.collect.ImmutableMap;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.languages.Swift3Codegen;
import java.util.Map;
public class Swift3OptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String SORT_MODEL_PROPERTIES_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String PROJECT_NAME_VALUE = "Swagger";
public static final String RESPONSE_AS_VALUE = "test";
public static final String UNWRAP_REQUIRED_VALUE = "true";
public static final String OBJC_COMPATIBLE_VALUE = "false";
public static final String LENIENT_TYPE_CAST_VALUE = "false";
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";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
@Override
public String getLanguage() {
return "swift3";
}
@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.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(Swift3Codegen.PROJECT_NAME, PROJECT_NAME_VALUE)
.put(Swift3Codegen.RESPONSE_AS, RESPONSE_AS_VALUE)
.put(Swift3Codegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE)
.put(Swift3Codegen.OBJC_COMPATIBLE, OBJC_COMPATIBLE_VALUE)
.put(Swift3Codegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_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")
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true")
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -1,144 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift3;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.Swift3Codegen;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Swift3CodegenTest {
Swift3Codegen swiftCodegen = new Swift3Codegen();
@Test(enabled = false)
public void testCapitalizedReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as");
}
@Test(enabled = false)
public void testReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public");
}
@Test(enabled = false)
public void shouldNotBreakNonReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error");
}
@Test(enabled = false)
public void shouldNotBreakCorrectName() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName");
}
@Test(enabled = false)
public void testSingleWordAllCaps() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value");
}
@Test(enabled = false)
public void testSingleWordLowercase() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value");
}
@Test(enabled = false)
public void testCapitalsWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName");
}
@Test(enabled = false)
public void testCapitalsWithDash() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName");
}
@Test(enabled = false)
public void testCapitalsWithSpace() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName");
}
@Test(enabled = false)
public void testLowercaseWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName");
}
@Test(enabled = false)
public void testStartingWithNumber() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName", null), "_123entryName");
Assert.assertEquals(swiftCodegen.toEnumVarName("123Entry_name", null), "_123entryName");
Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName123", null), "_123entryName123");
}
@Test(description = "returns NSData when response format is binary", enabled = false)
public void binaryDataTest() {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/binaryDataTest.json");
final DefaultCodegen codegen = new Swift3Codegen();
codegen.setOpenAPI(openAPI);
final String path = "/tests/binaryResponse";
final Operation p = openAPI.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
Assert.assertEquals(op.returnType, "Data");
Assert.assertEquals(op.bodyParam.dataType, "Data");
Assert.assertTrue(op.bodyParam.isBinary);
Assert.assertTrue(op.responses.get(0).isBinary);
}
@Test(description = "returns ISOFullDate when response format is date", enabled = false)
public void dateTest() {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
final DefaultCodegen codegen = new Swift3Codegen();
codegen.setOpenAPI(openAPI);
final String path = "/tests/dateResponse";
final Operation p = openAPI.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
Assert.assertEquals(op.returnType, "ISOFullDate");
Assert.assertEquals(op.bodyParam.dataType, "ISOFullDate");
}
@Test(enabled = false)
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(enabled = false)
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

@ -1,133 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift3;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.Swift3Codegen;
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 Schema schema = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
.addProperties("name", new StringSchema())
.addProperties("createdAt", new DateTimeSchema())
.addProperties("binary", new BinarySchema())
.addProperties("byte", new ByteArraySchema())
.addProperties("uuid", new UUIDSchema())
.addProperties("dateOfBirth", new DateSchema())
.addRequiredItem("id")
.addRequiredItem("name")
.discriminator(new Discriminator().propertyName("test"));
final DefaultCodegen codegen = new Swift3Codegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", schema);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 7);
Assert.assertEquals(cm.getDiscriminatorName(),"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.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.dataType, "String");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "String");
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertFalse(property2.isContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.dataType, "Date");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "Date");
Assert.assertTrue(property3.hasMore);
Assert.assertFalse(property3.required);
Assert.assertFalse(property3.isContainer);
final CodegenProperty property4 = cm.vars.get(3);
Assert.assertEquals(property4.baseName, "binary");
Assert.assertEquals(property4.dataType, "URL");
Assert.assertEquals(property4.name, "binary");
Assert.assertNull(property4.defaultValue);
Assert.assertEquals(property4.baseType, "URL");
Assert.assertTrue(property4.hasMore);
Assert.assertFalse(property4.required);
Assert.assertFalse(property4.isContainer);
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.assertFalse(property5.required);
Assert.assertFalse(property5.isContainer);
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.assertTrue(property6.hasMore);
Assert.assertFalse(property6.required);
Assert.assertFalse(property6.isContainer);
final CodegenProperty property7 = cm.vars.get(6);
Assert.assertEquals(property7.baseName, "dateOfBirth");
Assert.assertEquals(property7.dataType, "ISOFullDate");
Assert.assertEquals(property7.name, "dateOfBirth");
Assert.assertNull(property7.defaultValue);
Assert.assertEquals(property7.baseType, "ISOFullDate");
Assert.assertFalse(property7.hasMore);
Assert.assertFalse(property7.required);
Assert.assertFalse(property7.isContainer);
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift3;
import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.Swift3Codegen;
import org.openapitools.codegen.options.Swift3OptionsProvider;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class Swift3OptionsTest extends AbstractOptionsTest {
private Swift3Codegen clientCodegen = mock(Swift3Codegen.class, mockSettings);
public Swift3OptionsTest() {
super(new Swift3OptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void verifyOptions() {
verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.parseBoolean(Swift3OptionsProvider.SORT_PARAMS_VALUE));
verify(clientCodegen).setProjectName(Swift3OptionsProvider.PROJECT_NAME_VALUE);
verify(clientCodegen).setResponseAs(Swift3OptionsProvider.RESPONSE_AS_VALUE.split(","));
verify(clientCodegen).setUnwrapRequired(Boolean.parseBoolean(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE));
verify(clientCodegen).setObjcCompatible(Boolean.parseBoolean(Swift3OptionsProvider.OBJC_COMPATIBLE_VALUE));
verify(clientCodegen).setLenientTypeCast(Boolean.parseBoolean(Swift3OptionsProvider.LENIENT_TYPE_CAST_VALUE));
verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.parseBoolean(Swift3OptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE));
}
}

View File

@ -1,63 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

@ -1,63 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

@ -1 +0,0 @@
3.3.0-SNAPSHOT

View File

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

View File

@ -1,14 +0,0 @@
Pod::Spec.new do |s|
s.name = 'PetstoreClient'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.version = '0.0.1'
s.source = { :git => 'git@github.com:openapitools/openapi-generator.git', :tag => 'v1.0.0' }
s.authors = ''
s.license = 'Proprietary'
s.homepage = 'https://github.com/swagger-api/swagger-codegen'
s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/**/*.swift'
s.dependency 'Alamofire', '~> 3.5.1'
end

View File

@ -1,50 +0,0 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
class APIHelper {
static func rejectNil(source: [String: AnyObject?]) -> [String: AnyObject]? {
var destination = [String: AnyObject]()
for (key, nillableValue) in source {
if let value: AnyObject = nillableValue {
destination[key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
static func rejectNilHeaders(source: [String: AnyObject?]) -> [String: String] {
var destination = [String: String]()
for (key, nillableValue) in source {
if let value: AnyObject = nillableValue {
destination[key] = "\(value)"
}
}
return destination
}
static func convertBoolToString(source: [String: AnyObject]?) -> [String: AnyObject]? {
guard let source = source else {
return nil
}
var destination = [String: AnyObject]()
let theTrue = NSNumber(bool: true)
let theFalse = NSNumber(bool: false)
for (key, value) in source {
switch value {
case let x where x === theTrue || x === theFalse:
destination[key] = "\(value as! Bool)"
default:
destination[key] = value
}
}
return destination
}
}

View File

@ -1,76 +0,0 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class PetstoreClientAPI {
public static var basePath = "http://petstore.swagger.io/v2"
public static var credential: NSURLCredential?
public static var customHeaders: [String: String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
public class APIBase {
func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? {
let encoded: AnyObject? = encodable?.encodeToJSON()
if encoded! is [AnyObject] {
var dictionary = [String: AnyObject]()
for (index, item) in (encoded as! [AnyObject]).enumerate() {
dictionary["\(index)"] = item
}
return dictionary
} else {
return encoded as? [String: AnyObject]
}
}
}
public class RequestBuilder<T> {
var credential: NSURLCredential?
var headers: [String: String]
let parameters: [String: AnyObject]?
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: ((NSProgress) -> Void)?
required public init(method: String, URLString: String, parameters: [String: AnyObject]?, isBody: Bool, headers: [String: String] = [:]) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
self.headers = headers
addHeaders(PetstoreClientAPI.customHeaders)
}
public func addHeaders(aHeaders: [String: String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
public func addHeader(name name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
public func addCredential() -> Self {
self.credential = PetstoreClientAPI.credential
return self
}
}
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -1,483 +0,0 @@
//
// PetAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
public class PetAPI: APIBase {
/**
Add a new pet to the store
- parameter pet: (body) Pet object that needs to be added to the store (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func addPet(pet pet: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
addPetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Add a new pet to the store
- POST /pet - OAuth:
- type: oauth2
- name: petstore_auth
- parameter pet: (body) Pet object that needs to be added to the store (optional)
- returns: RequestBuilder<Void>
*/
public class func addPetWithRequestBuilder(pet pet: Pet? = nil) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = pet?.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 apiKey: (header) (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func deletePet(petId petId: Int64, apiKey: String? = nil, completion: ((error: ErrorType?) -> Void)) {
deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Deletes a pet
- DELETE /pet/{petId} - OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- returns: RequestBuilder<Void>
*/
public class func deletePetWithRequestBuilder(petId petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let nillableHeaders: [String: AnyObject?] = [
"api_key": apiKey
]
let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true, headers: headerParameters)
}
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in
completion(data: response?.body, error: 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/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- examples: [{contentType=application/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- parameter status: (query) Status values that need to be considered for filter (optional)
- returns: RequestBuilder<[Pet]>
*/
public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> {
let path = "/pet/findByStatus"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [
"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 (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in
completion(data: response?.body, error: 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/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- examples: [{contentType=application/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- parameter tags: (query) Tags to filter by (optional)
- returns: RequestBuilder<[Pet]>
*/
public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> {
let path = "/pet/findByTags"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [
"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 that needs to be fetched
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) {
getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
completion(data: response?.body, error: error)
}
}
/**
Find pet by ID
- GET /pet/{petId}
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - API Key:
- type: apiKey api_key
- name: api_key
- OAuth:
- type: oauth2
- name: petstore_auth
- examples: [{contentType=application/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- examples: [{contentType=application/json, example={
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}}, {contentType=application/xml, example=<Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>}]
- parameter petId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Pet>
*/
public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Pet> {
var path = "/pet/{petId}"
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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 pet: (body) Pet object that needs to be added to the store (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func updatePet(pet pet: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
updatePetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Update an existing pet
- PUT /pet - OAuth:
- type: oauth2
- name: petstore_auth
- parameter pet: (body) Pet object that needs to be added to the store (optional)
- returns: RequestBuilder<Void>
*/
public class func updatePetWithRequestBuilder(pet pet: Pet? = nil) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = pet?.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
*/
public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) {
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in
completion(error: 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>
*/
public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [
"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
*/
public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) {
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage - OAuth:
- type: oauth2
- name: petstore_auth
- 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<Void>
*/
public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}/uploadImage"
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [
"additionalMetadata": additionalMetadata,
"file": file
]
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)
}
}

View File

@ -1,206 +0,0 @@
//
// StoreAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
public 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
*/
public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) {
deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in
completion(error: 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>
*/
public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Void> {
var path = "/store/order/{orderId}"
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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
*/
public class func getInventory(completion: ((data: [String: Int32]?, error: ErrorType?) -> Void)) {
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: 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
- returns: RequestBuilder<[String:Int32]>
*/
public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int32]> {
let path = "/store/inventory"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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
*/
public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) {
getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
completion(data: response?.body, error: 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/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "placed"
}}, {contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}]
- examples: [{contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "placed"
}}, {contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}]
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Order> {
var path = "/store/order/{orderId}"
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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 order: (body) order placed for purchasing the pet (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func placeOrder(order order: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) {
placeOrderWithRequestBuilder(order: order).execute { (response, error) -> Void in
completion(data: response?.body, error: error)
}
}
/**
Place an order for a pet
- POST /store/order - examples: [{contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "placed"
}}, {contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}]
- examples: [{contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : true,
"status" : "placed"
}}, {contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}]
- parameter order: (body) order placed for purchasing the pet (optional)
- returns: RequestBuilder<Order>
*/
public class func placeOrderWithRequestBuilder(order order: Order? = nil) -> RequestBuilder<Order> {
let path = "/store/order"
let URLString = PetstoreClientAPI.basePath + path
let parameters = order?.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

@ -1,312 +0,0 @@
//
// UserAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
public class UserAPI: APIBase {
/**
Create user
- parameter user: (body) Created user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUser(user user: User? = nil, completion: ((error: ErrorType?) -> Void)) {
createUserWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Create user
- POST /user
- This can only be done by the logged in user. - parameter user: (body) Created user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUserWithRequestBuilder(user user: User? = nil) -> RequestBuilder<Void> {
let path = "/user"
let URLString = PetstoreClientAPI.basePath + path
let parameters = user?.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 user: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUsersWithArrayInput(user user: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
createUsersWithArrayInputWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Creates list of users with given input array
- POST /user/createWithArray - parameter user: (body) List of user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUsersWithArrayInputWithRequestBuilder(user user: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithArray"
let URLString = PetstoreClientAPI.basePath + path
let parameters = user?.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 user: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func createUsersWithListInput(user user: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
createUsersWithListInputWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Creates list of users with given input array
- POST /user/createWithList - parameter user: (body) List of user object (optional)
- returns: RequestBuilder<Void>
*/
public class func createUsersWithListInputWithRequestBuilder(user user: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithList"
let URLString = PetstoreClientAPI.basePath + path
let parameters = user?.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
*/
public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) {
deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in
completion(error: 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>
*/
public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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
*/
public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) {
getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in
completion(data: response?.body, error: error)
}
}
/**
Get user by user name
- GET /user/{username} - examples: [{contentType=application/json, example={
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
}}, {contentType=application/xml, example=<User>
<id>123456789</id>
<username>aeiou</username>
<firstName>aeiou</firstName>
<lastName>aeiou</lastName>
<email>aeiou</email>
<password>aeiou</password>
<phone>aeiou</phone>
<userStatus>123</userStatus>
</User>}]
- examples: [{contentType=application/json, example={
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
}}, {contentType=application/xml, example=<User>
<id>123456789</id>
<username>aeiou</username>
<firstName>aeiou</firstName>
<lastName>aeiou</lastName>
<email>aeiou</email>
<password>aeiou</password>
<phone>aeiou</phone>
<userStatus>123</userStatus>
</User>}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
*/
public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder<User> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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 (optional)
- parameter password: (query) The password for login in clear text (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) {
loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in
completion(data: response?.body, error: error)
}
}
/**
Logs user into the system
- GET /user/login - parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- returns: RequestBuilder<String>
*/
public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder<String> {
let path = "/user/login"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [
"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
*/
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
logoutUserWithRequestBuilder().execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Logs out current logged in user session
- GET /user/logout
- returns: RequestBuilder<Void>
*/
public class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let path = "/user/logout"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String: AnyObject?] = [:]
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 user: (body) Updated user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func updateUser(username username: String, user: User? = nil, completion: ((error: ErrorType?) -> Void)) {
updateUserWithRequestBuilder(username: username, user: user).execute { (_, error) -> Void in
completion(error: 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 user: (body) Updated user object (optional)
- returns: RequestBuilder<Void>
*/
public class func updateUserWithRequestBuilder(username username: String, user: User? = nil) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters = user?.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

@ -1,207 +0,0 @@
// AlamofireImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
}
public struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]()
private let queue = dispatch_queue_create("SynchronizedDictionary", DISPATCH_QUEUE_CONCURRENT)
public subscript(key: K) -> V? {
get {
var value: V?
dispatch_sync(queue) {
value = self.dictionary[key]
}
return value
}
set {
dispatch_barrier_sync(queue) {
self.dictionary[key] = newValue
}
}
}
}
// Store manager to retain its reference
private var managerStore = SynchronizedDictionary<String, Alamofire.Manager>()
class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required init(method: String, URLString: String, parameters: [String: AnyObject]?, isBody: Bool, headers: [String: String] = [:]) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers)
}
override func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) {
let managerId = NSUUID().UUIDString
// Create a new manager for each request to customize its request header
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = buildHeaders()
let manager = Alamofire.Manager(configuration: configuration)
managerStore[managerId] = manager
let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL
let xMethod = Alamofire.Method(rawValue: method)
let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(
xMethod!, URLString, headers: nil,
multipartFormData: { mpForm in
for (k, v) in self.parameters! {
switch v {
case let fileURL as NSURL:
mpForm.appendBodyPart(fileURL: fileURL, name: k)
case let string as NSString:
mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
case let number as NSNumber:
mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
default:
fatalError("Unprocessable value \(v) with key \(k)")
}
}
},
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let uploadRequest, _, _):
if let onProgressReady = self.onProgressReady {
onProgressReady(uploadRequest.progress)
}
self.processRequest(uploadRequest, managerId, completion)
case .Failure(let encodingError):
completion(response: nil, error: ErrorResponse.error(415, nil, encodingError))
}
}
)
} else {
let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request, managerId, completion)
}
}
private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response<T>?, error: ErrorType?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
managerStore[managerId] = nil
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
response: Response(
response: stringResponse.response!,
body: (stringResponse.result.value ?? "") as! T
),
error: nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
response: Response(
response: voidResponse.response!,
body: nil
),
error: nil
)
})
case is NSData.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if dataResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
response: Response(
response: dataResponse.response!,
body: dataResponse.data as! T
),
error: nil
)
})
default:
validatedRequest.responseJSON(options: .AllowFragments) { response in
cleanupRequest()
if response.result.isFailure {
completion(response: nil, error: ErrorResponse.error(response.response?.statusCode ?? 500, response.data, response.result.error!))
return
}
if () is T {
completion(response: Response(response: response.response!, body: () as! T), error: nil)
return
}
if let json: AnyObject = response.result.value {
let body = Decoders.decode(clazz: T.self, source: json)
completion(response: Response(response: response.response!, body: body), error: nil)
return
} else if "" is T {
completion(response: Response(response: response.response!, body: "" as! T), error: nil)
return
}
completion(response: nil, error: ErrorResponse.error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
}
}
}
private func buildHeaders() -> [String: AnyObject] {
var httpHeaders = Manager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
}

View File

@ -1,177 +0,0 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
extension Bool: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Float: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Int: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> AnyObject { return NSNumber(int: self) }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) }
}
extension Double: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
extension String: JSONEncodable {
func encodeToJSON() -> AnyObject { return self }
}
private func encodeIfPossible<T>(object: T) -> AnyObject {
if object is JSONEncodable {
return (object as! JSONEncodable).encodeToJSON()
} else {
return object as! AnyObject
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.map(encodeIfPossible)
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> AnyObject {
var dictionary = [NSObject: AnyObject]()
for (key, value) in self {
dictionary[key as! NSObject] = encodeIfPossible(value)
}
return dictionary
}
}
extension NSData: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
}
}
private let dateFormatter: NSDateFormatter = {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return fmt
}()
extension NSDate: JSONEncodable {
func encodeToJSON() -> AnyObject {
return dateFormatter.stringFromDate(self)
}
}
extension NSUUID: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.UUIDString
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}

View File

@ -1,234 +0,0 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> AnyObject
}
public enum ErrorResponse: ErrorType {
case Error(Int, NSData?, ErrorType)
}
public class Response<T> {
public let statusCode: Int
public let header: [String: String]
public 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: NSHTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String: String]()
for case let (key, value) as (String, String) in rawHeader {
header[key] = value
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
private var once = dispatch_once_t()
class Decoders {
static private var decoders = [String: ((AnyObject) -] AnyObject)>()
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
let key = "\(T.self)"
decoders[key] = { decoder($0) as! AnyObject }
}
static func decode<T>(clazz 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 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 clazz: T.Type, source: AnyObject) -> T {
initialize()
if T.self is Int32.Type && source is NSNumber {
return source.intValue as! T
}
if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T
}
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
}
if source is T {
return source as! T
}
if T.self is NSData.Type && source is String {
return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) 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 OpenAPI spec file is insufficient")
}
}
static func decodeOptional<T>(clazz 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 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 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)
}
}
static private func initialize() {
dispatch_once(&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) -> NSDateFormatter in
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = format
return formatter
}
// Decoder for NSDate
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.dateFromString(sourceString) {
return date
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
})
// 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! [NSObject: AnyObject]
let instance = Category()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
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! [NSObject: AnyObject]
let instance = Order()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"])
instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"])
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
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! [NSObject: AnyObject]
let instance = Pet()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"])
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"])
instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"])
instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
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! [NSObject: AnyObject]
let instance = Tag()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
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! [NSObject: AnyObject]
let instance = User()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"])
instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"])
instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"])
return instance
}
}
}
}

View File

@ -1,24 +0,0 @@
//
// Category.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class Category: JSONEncodable {
public var id: Int64?
public var name: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String: AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["name"] = self.name
let dictionary: [String: AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -1,38 +0,0 @@
//
// Order.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class Order: JSONEncodable {
public enum Status: String {
case Placed = "placed"
case Approved = "approved"
case Delivered = "delivered"
}
public var id: Int64?
public var petId: Int64?
public var quantity: Int32?
public var shipDate: NSDate?
/** Order Status */
public var status: Status?
public var complete: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String: AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["petId"] = self.petId?.encodeToJSON()
nillableDictionary["quantity"] = self.quantity?.encodeToJSON()
nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON()
nillableDictionary["status"] = self.status?.rawValue
nillableDictionary["complete"] = self.complete
let dictionary: [String: AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -1,38 +0,0 @@
//
// Pet.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class Pet: JSONEncodable {
public enum Status: String {
case Available = "available"
case Pending = "pending"
case Sold = "sold"
}
public var id: Int64?
public var category: Category?
public var name: String?
public var photoUrls: [String]?
public var tags: [Tag]?
/** pet status in the store */
public var status: Status?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String: AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["category"] = self.category?.encodeToJSON()
nillableDictionary["name"] = self.name
nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON()
nillableDictionary["tags"] = self.tags?.encodeToJSON()
nillableDictionary["status"] = self.status?.rawValue
let dictionary: [String: AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -1,24 +0,0 @@
//
// Tag.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class Tag: JSONEncodable {
public var id: Int64?
public var name: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String: AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["name"] = self.name
let dictionary: [String: AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -1,37 +0,0 @@
//
// User.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?
public var firstName: String?
public var lastName: String?
public var email: String?
public var password: String?
public var phone: String?
/** User Status */
public var userStatus: Int32?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String: AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["username"] = self.username
nillableDictionary["firstName"] = self.firstName
nillableDictionary["lastName"] = self.lastName
nillableDictionary["email"] = self.email
nillableDictionary["password"] = self.password
nillableDictionary["phone"] = self.phone
nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON()
let dictionary: [String: AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}

View File

@ -1,11 +0,0 @@
use_frameworks!
source 'https://github.com/CocoaPods/Specs.git'
target 'SwaggerClient' do
pod "PetstoreClient", :path => "../"
target 'SwaggerClientTests' do
inherit! :search_paths
end
end

View File

@ -1,529 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; };
6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; };
6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; };
6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */; };
6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */; };
6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; };
6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; };
6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; };
A77F0668DAC6BFAB9DBB7D37 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9AE2FEF8E8F914C1D2F168B /* Pods_SwaggerClient.framework */; };
C6AAAD211D8718D00016A515 /* ISOFullDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */; };
F3FCC41175F14274266B53FA /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A3C56BADD08FA3D474DBDF71 /* Pods_SwaggerClientTests.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6D4EFB891C692C6300B96B06 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 6D4EFB901C692C6300B96B06;
remoteInfo = SwaggerClient;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; };
6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
6D4EFB991C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
6D4EFB9E1C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
6D4EFBA01C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwaggerClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
6D4EFBAB1C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = "<group>"; };
6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = "<group>"; };
6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = "<group>"; };
78ED7EF301CC6DF958B4BFAB /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = "<group>"; };
A3C56BADD08FA3D474DBDF71 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ISOFullDateTests.swift; sourceTree = "<group>"; };
E9AE2FEF8E8F914C1D2F168B /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; };
EA2BED756A4C5389B0F46BC4 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = "<group>"; };
EA32712FFC62EA5F96CC006F /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = "<group>"; };
F18FDCB0CAAA15B973147EED /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
6D4EFB8E1C692C6300B96B06 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A77F0668DAC6BFAB9DBB7D37 /* Pods_SwaggerClient.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6D4EFBA21C692C6300B96B06 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F3FCC41175F14274266B53FA /* Pods_SwaggerClientTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
3FABC56EC0BA84CBF4F99564 /* Frameworks */ = {
isa = PBXGroup;
children = (
C07EC0A94AA0F86D60668B32 /* Pods.framework */,
E9AE2FEF8E8F914C1D2F168B /* Pods_SwaggerClient.framework */,
A3C56BADD08FA3D474DBDF71 /* Pods_SwaggerClientTests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
6D4EFB881C692C6300B96B06 = {
isa = PBXGroup;
children = (
6D4EFB931C692C6300B96B06 /* SwaggerClient */,
6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */,
6D4EFB921C692C6300B96B06 /* Products */,
3FABC56EC0BA84CBF4F99564 /* Frameworks */,
D598C75400476D9194EADBAA /* Pods */,
);
sourceTree = "<group>";
};
6D4EFB921C692C6300B96B06 /* Products */ = {
isa = PBXGroup;
children = (
6D4EFB911C692C6300B96B06 /* SwaggerClient.app */,
6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
6D4EFB931C692C6300B96B06 /* SwaggerClient */ = {
isa = PBXGroup;
children = (
6D4EFB941C692C6300B96B06 /* AppDelegate.swift */,
6D4EFB961C692C6300B96B06 /* ViewController.swift */,
6D4EFB981C692C6300B96B06 /* Main.storyboard */,
6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */,
6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */,
6D4EFBA01C692C6300B96B06 /* Info.plist */,
);
path = SwaggerClient;
sourceTree = "<group>";
};
6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */ = {
isa = PBXGroup;
children = (
6D4EFBAB1C692C6300B96B06 /* Info.plist */,
C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */,
6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */,
6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */,
6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */,
);
path = SwaggerClientTests;
sourceTree = "<group>";
};
D598C75400476D9194EADBAA /* Pods */ = {
isa = PBXGroup;
children = (
EA2BED756A4C5389B0F46BC4 /* Pods-SwaggerClient.debug.xcconfig */,
F18FDCB0CAAA15B973147EED /* Pods-SwaggerClient.release.xcconfig */,
78ED7EF301CC6DF958B4BFAB /* Pods-SwaggerClientTests.debug.xcconfig */,
EA32712FFC62EA5F96CC006F /* Pods-SwaggerClientTests.release.xcconfig */,
);
name = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
6D4EFB901C692C6300B96B06 /* SwaggerClient */ = {
isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = (
E5F6E842A9A53DF5152241BC /* [CP] Check Pods Manifest.lock */,
6D4EFB8D1C692C6300B96B06 /* Sources */,
6D4EFB8E1C692C6300B96B06 /* Frameworks */,
6D4EFB8F1C692C6300B96B06 /* Resources */,
4A8C29C17AE187506924CE72 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = SwaggerClient;
productName = SwaggerClient;
productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */;
productType = "com.apple.product-type.application";
};
6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = (
18CD551FE8D8E7492A1C4100 /* [CP] Check Pods Manifest.lock */,
6D4EFBA11C692C6300B96B06 /* Sources */,
6D4EFBA21C692C6300B96B06 /* Frameworks */,
6D4EFBA31C692C6300B96B06 /* Resources */,
);
buildRules = (
);
dependencies = (
6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */,
);
name = SwaggerClientTests;
productName = SwaggerClientTests;
productReference = 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
6D4EFB891C692C6300B96B06 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0720;
LastUpgradeCheck = 0720;
ORGANIZATIONNAME = Swagger;
TargetAttributes = {
6D4EFB901C692C6300B96B06 = {
CreatedOnToolsVersion = 7.2.1;
};
6D4EFBA41C692C6300B96B06 = {
CreatedOnToolsVersion = 7.2.1;
TestTargetID = 6D4EFB901C692C6300B96B06;
};
};
};
buildConfigurationList = 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 6D4EFB881C692C6300B96B06;
productRefGroup = 6D4EFB921C692C6300B96B06 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
6D4EFB901C692C6300B96B06 /* SwaggerClient */,
6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
6D4EFB8F1C692C6300B96B06 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */,
6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */,
6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6D4EFBA31C692C6300B96B06 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
18CD551FE8D8E7492A1C4100 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
4A8C29C17AE187506924CE72 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework",
"${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
);
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
E5F6E842A9A53DF5152241BC /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
6D4EFB8D1C692C6300B96B06 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */,
6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6D4EFBA11C692C6300B96B06 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C6AAAD211D8718D00016A515 /* ISOFullDateTests.swift in Sources */,
6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */,
6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */,
6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 6D4EFB901C692C6300B96B06 /* SwaggerClient */;
targetProxy = 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
6D4EFB981C692C6300B96B06 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
6D4EFB991C692C6300B96B06 /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
6D4EFB9E1C692C6300B96B06 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
6D4EFBAC1C692C6300B96B06 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.2;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
6D4EFBAD1C692C6300B96B06 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.2;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
6D4EFBAF1C692C6300B96B06 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = EA2BED756A4C5389B0F46BC4 /* Pods-SwaggerClient.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
INFOPLIST_FILE = SwaggerClient/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
6D4EFBB01C692C6300B96B06 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = F18FDCB0CAAA15B973147EED /* Pods-SwaggerClient.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
INFOPLIST_FILE = SwaggerClient/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
6D4EFBB21C692C6300B96B06 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 78ED7EF301CC6DF958B4BFAB /* Pods-SwaggerClientTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
INFOPLIST_FILE = SwaggerClientTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests;
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient";
};
name = Debug;
};
6D4EFBB31C692C6300B96B06 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = EA32712FFC62EA5F96CC006F /* Pods-SwaggerClientTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
INFOPLIST_FILE = SwaggerClientTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests;
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6D4EFBAC1C692C6300B96B06 /* Debug */,
6D4EFBAD1C692C6300B96B06 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6D4EFBAF1C692C6300B96B06 /* Debug */,
6D4EFBB01C692C6300B96B06 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6D4EFBB21C692C6300B96B06 /* Debug */,
6D4EFBB31C692C6300B96B06 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 6D4EFB891C692C6300B96B06 /* Project object */;
}

View File

@ -1,102 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES"
hideIssues = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6D4EFB901C692C6300B96B06"
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6D4EFBA41C692C6300B96B06"
BuildableName = "SwaggerClientTests.xctest"
BlueprintName = "SwaggerClientTests"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6D4EFB901C692C6300B96B06"
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6D4EFB901C692C6300B96B06"
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6D4EFB901C692C6300B96B06"
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:SwaggerClient.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>

View File

@ -1,43 +0,0 @@
//
// AppDelegate.swift
// SwaggerClient
//
// Created by Joseph Zuromski on 2/8/16.
// Copyright © 2016 Swagger. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

View File

@ -1,73 +0,0 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>

View File

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

View File

@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>petstore.swagger.io</key>
<dict>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>

View File

@ -1,23 +0,0 @@
//
// ViewController.swift
// SwaggerClient
//
// Created by Joseph Zuromski on 2/8/16.
// Copyright © 2016 Swagger. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

View File

@ -1,83 +0,0 @@
/// Copyright 2012-2016 (C) Butterfly Network, Inc.
import PetstoreClient
import XCTest
@testable import SwaggerClient
final class ISOFullDateTests: XCTestCase {
var fullDate = ISOFullDate(year: 1999, month: 12, day: 31)
func testValidDate() {
XCTAssertEqual(fullDate.year, 1999)
XCTAssertEqual(fullDate.month, 12)
XCTAssertEqual(fullDate.day, 31)
}
func testFromDate() {
let date = NSDate()
let fullDate = ISOFullDate.from(date: date)
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
XCTFail()
return
}
let components = calendar.components(
[
.Year,
.Month,
.Day
],
fromDate: date
)
XCTAssertEqual(fullDate?.year, components.year)
XCTAssertEqual(fullDate?.month, components.month)
XCTAssertEqual(fullDate?.day, components.day)
}
func testFromString() {
let string = "1999-12-31"
let fullDate = ISOFullDate.from(string: string)
XCTAssertEqual(fullDate?.year, 1999)
XCTAssertEqual(fullDate?.month, 12)
XCTAssertEqual(fullDate?.day, 31)
}
func testFromInvalidString() {
XCTAssertNil(ISOFullDate.from(string: "1999-12"))
}
func testToDate() {
let fullDate = ISOFullDate(year: 1999, month: 12, day: 31)
guard let date = fullDate.toDate(),
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
XCTFail()
return
}
let components = calendar.components(
[
.Year,
.Month,
.Day
],
fromDate: date
)
XCTAssertEqual(fullDate.year, components.year)
XCTAssertEqual(fullDate.month, components.month)
XCTAssertEqual(fullDate.day, components.day)
}
func testDescription() {
XCTAssertEqual(fullDate.description, "1999-12-31")
}
func testEncodeToJSON() {
XCTAssertEqual(fullDate.encodeToJSON() as? String, "1999-12-31")
}
}

View File

@ -1,36 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>petstore.swagger.io</key>
<dict>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>

View File

@ -1,86 +0,0 @@
//
// PetAPITests.swift
// SwaggerClient
//
// Created by Robin Eggenkamp on 5/21/16.
// Copyright © 2016 Swagger. All rights reserved.
//
import PetstoreClient
import XCTest
@testable import SwaggerClient
class PetAPITests: XCTestCase {
let testTimeout = 10.0
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test1CreatePet() {
let expectation = self.expectationWithDescription("testCreatePet")
let newPet = Pet()
let category = PetstoreClient.Category()
category.id = 1234
category.name = "eyeColor"
newPet.category = category
newPet.id = 1000
newPet.name = "Fluffy"
newPet.status = .Available
PetAPI.addPet(body: newPet) { (error) in
guard error == nil else {
XCTFail("error creating pet")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test2GetPet() {
let expectation = self.expectationWithDescription("testGetPet")
PetAPI.getPetById(petId: 1000) { (pet, error) in
guard error == nil else {
XCTFail("error retrieving pet")
return
}
if let pet = pet {
XCTAssert(pet.id == 1000, "invalid id")
XCTAssert(pet.name == "Fluffy", "invalid name")
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test3DeletePet() {
let expectation = self.expectationWithDescription("testDeletePet")
PetAPI.deletePet(petId: 1000) { (error) in
guard error == nil else {
XCTFail("error deleting pet")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
}

View File

@ -1,122 +0,0 @@
//
// StoreAPITests.swift
// SwaggerClient
//
// Created by Robin Eggenkamp on 5/21/16.
// Copyright © 2016 Swagger. All rights reserved.
//
import PetstoreClient
import XCTest
@testable import SwaggerClient
class StoreAPITests: XCTestCase {
let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let testTimeout = 10.0
func test1PlaceOrder() {
let expectation = self.expectationWithDescription("testPlaceOrder")
let shipDate = NSDate()
let newOrder = Order()
newOrder.id = 1000
newOrder.petId = 1000
newOrder.complete = false
newOrder.quantity = 10
newOrder.shipDate = shipDate
// use explicit naming to reference the enum so that we test we don't regress on enum naming
newOrder.status = Order.Status.Placed
StoreAPI.placeOrder(body: newOrder) { (order, error) in
guard error == nil else {
XCTFail("error placing order: \(error.debugDescription)")
return
}
if let order = order {
XCTAssert(order.id == 1000, "invalid id")
XCTAssert(order.quantity == 10, "invalid quantity")
XCTAssert(order.status == .Placed, "invalid status")
XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat),
"Date should be idempotent")
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test2GetOrder() {
let expectation = self.expectationWithDescription("testGetOrder")
StoreAPI.getOrderById(orderId: "1000") { (order, error) in
guard error == nil else {
XCTFail("error retrieving order: \(error.debugDescription)")
return
}
if let order = order {
XCTAssert(order.id == 1000, "invalid id")
XCTAssert(order.quantity == 10, "invalid quantity")
XCTAssert(order.status == .Placed, "invalid status")
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test3DeleteOrder() {
let expectation = self.expectationWithDescription("testDeleteOrder")
StoreAPI.deleteOrder(orderId: "1000") { (error) in
guard error == nil else {
XCTFail("error deleting order")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func testDownloadProgress() {
let responseExpectation = self.expectationWithDescription("obtain response")
let progressExpectation = self.expectationWithDescription("obtain progress")
let requestBuilder = StoreAPI.getOrderByIdWithRequestBuilder(orderId: "1000")
requestBuilder.onProgressReady = { (progress) in
progressExpectation.fulfill()
}
requestBuilder.execute { (_, _) in
responseExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
}
private extension NSDate {
/**
Returns true if the dates are equal given the format string.
- parameter date: The date to compare to.
- parameter format: The format string to use to compare.
- returns: true if the dates are equal, given the format string.
*/
func isEqual(date: NSDate, format: String) -> Bool {
let fmt = NSDateFormatter()
fmt.dateFormat = format
return fmt.stringFromDate(self).isEqual(fmt.stringFromDate(date))
}
}

View File

@ -1,119 +0,0 @@
//
// UserAPITests.swift
// SwaggerClient
//
// Created by Robin Eggenkamp on 5/21/16.
// Copyright © 2016 Swagger. All rights reserved.
//
import PetstoreClient
import XCTest
@testable import SwaggerClient
class UserAPITests: XCTestCase {
let testTimeout = 10.0
func testLogin() {
let expectation = self.expectationWithDescription("testLogin")
UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in
guard error == nil else {
XCTFail("error logging in")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func testLogout() {
let expectation = self.expectationWithDescription("testLogout")
UserAPI.logoutUser { (error) in
guard error == nil else {
XCTFail("error logging out")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test1CreateUser() {
let expectation = self.expectationWithDescription("testCreateUser")
let newUser = User()
newUser.email = "test@test.com"
// TODO comment out the following as dateOfBirth has been removed
// from petstore.json, we'll need to add back the test after switching
// to petstore-with-fake-endpoints-models-for-testing.yaml
////newUser.dateOfBirth = ISOFullDate.from(string: "1999-12-31")
newUser.firstName = "Test"
newUser.lastName = "Tester"
newUser.id = 1000
newUser.password = "test!"
newUser.phone = "867-5309"
newUser.username = "test@test.com"
newUser.userStatus = 0
UserAPI.createUser(body: newUser) { (error) in
guard error == nil else {
XCTFail("error creating user")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test2GetUser() {
let expectation = self.expectationWithDescription("testGetUser")
UserAPI.getUserByName(username: "test@test.com") { (user, error) in
guard error == nil else {
XCTFail("error getting user")
return
}
if let user = user {
XCTAssert(user.userStatus == 0, "invalid userStatus")
XCTAssert(user.email == "test@test.com", "invalid email")
XCTAssert(user.firstName == "Test", "invalid firstName")
XCTAssert(user.lastName == "Tester", "invalid lastName")
XCTAssert(user.password == "test!", "invalid password")
XCTAssert(user.phone == "867-5309", "invalid phone")
// TODO comment out the following as dateOfBirth has been removed
// from petstore.json, we'll need to add back the test after switching
// to petstore-with-fake-endpoints-models-for-testing.yaml
//XCTAssert(user.dateOfBirth?.description == "1999-12-31", "invalid date of birth")
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test3DeleteUser() {
let expectation = self.expectationWithDescription("testDeleteUser")
UserAPI.deleteUser(username: "test@test.com") { (error) in
guard error == nil else {
XCTFail("error deleting user")
return
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
}

View File

@ -1,43 +0,0 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>SwiftPetstoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Swift Swagger Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>xcodebuild-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>./run_xcodebuild.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,5 +0,0 @@
#!/bin/sh
#pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
pod install && xcodebuild -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" test -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" | xcpretty

View File

@ -1,52 +0,0 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://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

@ -1,63 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

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