New generator swift5 (#4086)

* [swift5] introduce new generator

* [swift5] add Swift Package Manager integration and update dependencies

* [swift5] run petstore

* [swift] update Swift 5 generator with Swift 4 changes

* [swift] update Swift 5 generator with Swift 4 changes

* [swift] make CodableHelper more customizable

* [swift] update pet projects

* [swift] update pet projects

* [swift] add nullable support

* [swift] make enums conform to CaseIterable

* [swift] date formatter add support for ISO8601 with and without milliseconds

* [swift] add urlsession support

* [swift] remove unecessary sample unwrapRequired

* [swift] rename JSONEncodableEncoding.swift to JSONDataEncoding.swift

* [swift] use result in generator internals

* [swift] cocoapods remove deprecated docset_url and add watchos deployment target

* [swift] Add ability to pass in a dedicated queue for processing network response (Fix for 230)

* [swift] update pet projects

* [swift] update docs

* [swift] add support for combine

* [swift] update docs

* [swift] update windows bat scripts

* [swift] update windows bat scripts

* [swift] update swift pet project tests

* [swift] update depencies

* [swift] make urlsession the default http client

* [swift] add urlsession sample project

* [swift] add urlsession sample project

* [swift] update docs

* [swift] improve combine unit tests

* [swift] update docs
This commit is contained in:
Bruno Coelho 2020-01-02 12:21:45 +00:00 committed by William Cheng
parent 39ba6bbfb1
commit 5cc5fbe76a
1448 changed files with 84540 additions and 781 deletions

View File

@ -49,6 +49,25 @@ workflows:
./samples/client/petstore/swift4/swift4_test_all.sh
./samples/client/test/swift4/swift4_test_all.sh
- script@1.1.5:
title: Update Swift5 samples
inputs:
- content: |
#!/usr/bin/env bash
set -e
sh bin/swift5-all.sh
- script@1.1.5:
title: Run Swift5 tests
inputs:
- content: |
#!/usr/bin/env bash
set -e
./samples/client/petstore/swift5/swift5_test_all.sh
./samples/client/test/swift5/swift5_test_all.sh
- script@1.1.5:
title: Run all bin scripts
inputs:

4
bin/swift5-all.sh Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
./bin/swift5-petstore-all.sh
./bin/swift5-test.sh

View File

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

View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-alamofire.json -o samples/client/petstore/swift5/alamofireLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/alamofireLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/alamofireLibrary
swiftlint autocorrect
fi

12
bin/swift5-petstore-all.sh Executable file
View File

@ -0,0 +1,12 @@
#!/bin/sh
./bin/swift5-petstore.sh
./bin/swift5-petstore-promisekit.sh
./bin/swift5-petstore-result.sh
./bin/swift5-petstore-rxswift.sh
./bin/swift5-petstore-objcCompatible.sh
./bin/swift5-petstore-nonPublicApi.sh
./bin/swift5-petstore-urlsession.sh
./bin/swift5-petstore-alamofire.sh
./bin/swift5-petstore-combine.sh

View File

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

42
bin/swift5-petstore-combine.sh Executable file
View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-combine.json -o samples/client/petstore/swift5/combineLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/combineLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/combineLibrary
swiftlint autocorrect
fi

View File

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

View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-nonPublicApi.json -o samples/client/petstore/swift5/nonPublicApi --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/nonPublicApi
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/nonPublicApi
swiftlint autocorrect
fi

View File

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

View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-objcCompatible.json -o samples/client/petstore/swift5/objcCompatible --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/objcCompatible
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/objcCompatible
swiftlint autocorrect
fi

View File

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

View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-promisekit.json -o samples/client/petstore/swift5/promisekitLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/promisekitLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/promisekitLibrary
swiftlint autocorrect
fi

View File

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

42
bin/swift5-petstore-result.sh Executable file
View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-result.json -o samples/client/petstore/swift5/resultLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/resultLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/resultLibrary
swiftlint autocorrect
fi

View File

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

42
bin/swift5-petstore-rxswift.sh Executable file
View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-rxswift.json -o samples/client/petstore/swift5/rxswiftLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/rxswiftLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/rxswiftLibrary
swiftlint autocorrect
fi

View File

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

View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-urlsession.json -o samples/client/petstore/swift5/urlsessionLibrary --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/urlsessionLibrary
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/urlsessionLibrary
swiftlint autocorrect
fi

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

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

42
bin/swift5-petstore.sh Executable file
View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore.json -o samples/client/petstore/swift5/default --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/default
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift5/default
swiftlint autocorrect
fi

6
bin/swift5-test.json Normal file
View File

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

42
bin/swift5-test.sh Executable file
View File

@ -0,0 +1,42 @@
#!/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/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift5Test.json -g swift5 -c ./bin/swift5-test.json -o samples/client/test/swift5/default --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/test/swift5/default
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/test/swift5/default
swiftlint autocorrect
fi

2
bin/windows/swift5-all.bat Executable file
View File

@ -0,0 +1,2 @@
call .\bin\windows\swift5-petstore-all.bat
call .\bin\windows\swift5-test.bat

View File

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

View File

@ -0,0 +1,9 @@
call .\bin\windows\swift5-petstore.bat
call .\bin\windows\swift5-petstore-promisekit.bat
call .\bin\windows\swift5-petstore-result.bat
call .\bin\windows\swift5-petstore-rxswift.bat
call .\bin\windows\swift5-petstore-objcCompatible.bat
call .\bin\windows\swift5-petstore-nonPublicApi.bat
call .\bin\windows\swift5-petstore-urlsession.bat
call .\bin\windows\swift5-petstore-alamofire.bat
call .\bin\windows\swift5-petstore-combine.bat

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

10
bin/windows/swift5-petstore.bat Executable file
View File

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

10
bin/windows/swift5-test.bat Executable file
View File

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

View File

@ -57,6 +57,7 @@ The following generators are available:
* [swift2-deprecated (deprecated)](generators/swift2-deprecated.md)
* [swift3-deprecated (deprecated)](generators/swift3-deprecated.md)
* [swift4](generators/swift4.md)
* [swift5](generators/swift5.md)
* [typescript-angular](generators/typescript-angular.md)
* [typescript-angularjs](generators/typescript-angularjs.md)
* [typescript-aurelia](generators/typescript-aurelia.md)

31
docs/generators/swift5.md Normal file
View File

@ -0,0 +1,31 @@
---
title: Config Options for swift5
sidebar_label: swift5
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|projectName|Project name in Xcode| |null|
|responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result, Combine are available.| |null|
|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null|
|objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null|
|podSource|Source information used for Podspec| |null|
|podVersion|Version used for Podspec| |null|
|podAuthors|Authors used for Podspec| |null|
|podSocialMediaURL|Social Media URL used for Podspec| |null|
|podLicense|License used for Podspec| |null|
|podHomepage|Homepage used for Podspec| |null|
|podSummary|Summary used for Podspec| |null|
|podDescription|Description used for Podspec| |null|
|podScreenshots|Screenshots used for Podspec| |null|
|podDocumentationURL|Documentation URL used for Podspec| |null|
|swiftUseApiNamespace|Flag to make all the API classes inner-class of {{projectName}}API| |null|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false|
|library|Library template (sub-template) to use|<dl><dt>**urlsession**</dt><dd>[DEFAULT] HTTP client: URLSession</dd><dt>**alamofire**</dt><dd>HTTP client: Alamofire</dd><dl>|urlsession|

View File

@ -109,6 +109,7 @@ org.openapitools.codegen.languages.StaticHtml2Generator
org.openapitools.codegen.languages.SwiftClientCodegen
org.openapitools.codegen.languages.Swift3Codegen
org.openapitools.codegen.languages.Swift4Codegen
org.openapitools.codegen.languages.Swift5Codegen
org.openapitools.codegen.languages.TypeScriptAngularClientCodegen
org.openapitools.codegen.languages.TypeScriptAngularJsClientCodegen
org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen

View File

@ -0,0 +1,71 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct APIHelper {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNil(_ source: [String:Any?]) -> [String:Any]? {
let destination = source.reduce(into: [String: Any]()) { (result, item) in
if let value = item.value {
result[item.key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] {
return source.reduce(into: [String: String]()) { (result, item) in
if let collection = item.value as? Array<Any?> {
result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",")
} else if let value: Any = item.value {
result[item.key] = "\(value)"
}
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? {
guard let source = source else {
return nil
}
return source.reduce(into: [String: Any](), { (result, item) in
switch item.value {
case let x as Bool:
result[item.key] = x.description
default:
result[item.key] = item.value
}
})
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValueToPathItem(_ source: Any) -> Any {
if let collection = source as? Array<Any?> {
return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",")
}
return source
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? {
let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in
if let collection = item.value as? Array<Any?> {
let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",")
result.append(URLQueryItem(name: item.key, value: value))
} else if let value = item.value {
result.append(URLQueryItem(name: item.key, value: "\(value)"))
}
}
if destination.isEmpty {
return nil
}
return destination
}
}

View File

@ -0,0 +1,65 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var basePath = "{{{basePath}}}"
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential?
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String:String] = [:]{{#useAlamofire}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory(){{/useAlamofire}}{{#useURLSession}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory(){{/useURLSession}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiResponseQueue: DispatchQueue = .main
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String:String]
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let parameters: [String:Any]?
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let isBody: Bool
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let method: String
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.{{#useURLSession}}
/// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0.
/// If you need to get the request's progress in older OS versions, please use Alamofire http client.{{/useURLSession}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> ())?
required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: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)
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Result<Response<T>, Error>) -> Void) { }
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addCredential() -> Self {
self.credential = {{projectName}}API.credential
return self
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type
}

View File

@ -0,0 +1,3 @@
{{#useAlamofire}}github "Alamofire/Alamofire" ~> 4.9.1{{/useAlamofire}}{{#usePromiseKit}}
github "mxcl/PromiseKit" ~> 6.12.0{{/usePromiseKit}}{{#useRxSwift}}
github "ReactiveX/RxSwift" ~> 5.0.1{{/useRxSwift}}

View File

@ -0,0 +1,48 @@
//
// CodableHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class CodableHelper {
private static var customDateFormatter: DateFormatter?
private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter()
private static var customJSONDecoder: JSONDecoder?
private static var defaultJSONDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter)
return decoder
}()
private static var customJSONEncoder: JSONEncoder?
private static var defaultJSONEncoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter)
encoder.outputFormatting = .prettyPrinted
return encoder
}()
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormatter: DateFormatter {
get { return self.customDateFormatter ?? self.defaultDateFormatter }
set { self.customDateFormatter = newValue }
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var jsonDecoder: JSONDecoder {
get { return self.customJSONDecoder ?? self.defaultJSONDecoder }
set { self.customJSONDecoder = newValue }
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var jsonEncoder: JSONEncoder {
get { return self.customJSONEncoder ?? self.defaultJSONEncoder }
set { self.customJSONEncoder = newValue }
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func decode<T>(_ type: T.Type, from data: Data) -> Result<T, Error> where T: Decodable {
return Result { try self.jsonDecoder.decode(type, from: data) }
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encode<T>(_ value: T) -> Result<Data, Error> where T: Encodable {
return Result { try self.jsonEncoder.encode(value) }
}
}

View File

@ -0,0 +1,16 @@
// Configuration.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Configuration {
// This value is used to configure the date formatter that is used to serialize dates into JSON format.
// You must set it prior to encoding any dates, and it will only be read once.
@available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.")
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
}

View File

@ -0,0 +1,189 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation{{#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 }
}
extension RawRepresentable where RawValue: JSONEncodable {
func encodeToJSON() -> Any { return self.rawValue 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())
}
}
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return CodableHelper.dateFormatter.string(from: self) as Any
}
}
extension URL: JSONEncodable {
func encodeToJSON() -> Any {
return self
}
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any {
return self.uuidString
}
}
extension String: CodingKey {
public var stringValue: String {
return self
}
public init?(stringValue: String) {
self.init(stringLiteral: stringValue)
}
public var intValue: Int? {
return nil
}
public init?(intValue: Int) {
return nil
}
}
extension KeyedEncodingContainerProtocol {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArray<T>(_ values: [T], forKey key: Self.Key) throws where T : Encodable {
var arrayContainer = nestedUnkeyedContainer(forKey: key)
try arrayContainer.encode(contentsOf: values)
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArrayIfPresent<T>(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable {
if let values = values {
try encodeArray(values, forKey: key)
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMap<T>(_ pairs: [Self.Key: T]) throws where T : Encodable {
for (key, value) in pairs {
try encode(value, forKey: key)
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMapIfPresent<T>(_ pairs: [Self.Key: T]?) throws where T : Encodable {
if let pairs = pairs {
try encodeMap(pairs)
}
}
}
extension KeyedDecodingContainerProtocol {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArray<T>(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable {
var tmpArray = [T]()
var nestedContainer = try nestedUnkeyedContainer(forKey: key)
while !nestedContainer.isAtEnd {
let arrayValue = try nestedContainer.decode(T.self)
tmpArray.append(arrayValue)
}
return tmpArray
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArrayIfPresent<T>(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable {
var tmpArray: [T]? = nil
if contains(key) {
tmpArray = try decodeArray(T.self, forKey: key)
}
return tmpArray
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeMap<T>(_ type: T.Type, excludedKeys: Set<Self.Key>) throws -> [Self.Key: T] where T : Decodable {
var map: [Self.Key : T] = [:]
for key in allKeys {
if !excludedKeys.contains(key) {
let value = try decode(T.self, forKey: key)
map[key] = value
}
}
return map
}
}
{{#usePromiseKit}}extension RequestBuilder {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pending()
self.execute { result in
switch result {
case let .success(response):
deferred.resolver.fulfill(response)
case let .failure(error):
deferred.resolver.reject(error)
}
}
return deferred.promise
}
}{{/usePromiseKit}}

View File

@ -0,0 +1,53 @@
//
// JSONDataEncoding.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct JSONDataEncoding {
// MARK: Properties
private static let jsonDataKey = "jsonData"
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply. This should have a single key/value
/// pair with "jsonData" as the key and a Data object as the value.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest {
var urlRequest = urlRequest
guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else {
return urlRequest
}
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = jsonData
return urlRequest
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func encodingParameters(jsonData: Data?) -> [String: Any]? {
var returnedParams: [String: Any]? = nil
if let jsonData = jsonData, !jsonData.isEmpty {
var params: [String: Any] = [:]
params[jsonDataKey] = jsonData
returnedParams = params
}
return returnedParams
}
}

View File

@ -0,0 +1,45 @@
//
// JSONEncodingHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class JSONEncodingHelper {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters<T:Encodable>(forEncodableObject encodableObj: T?) -> [String: Any]? {
var params: [String: Any]? = nil
// Encode the Encodable object
if let encodableObj = encodableObj {
let encodeResult = CodableHelper.encode(encodableObj)
do {
let data = try encodeResult.get()
params = JSONDataEncoding.encodingParameters(jsonData: data)
} catch {
print(error.localizedDescription)
}
}
return params
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? {
var params: [String: Any]? = nil
if let encodableObj = encodableObj {
do {
let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted)
params = JSONDataEncoding.encodingParameters(jsonData: data)
} catch {
print(error.localizedDescription)
return nil
}
}
return params
}
}

View File

@ -0,0 +1,52 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> Any
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse : Error {
case error(Int, Data?, Error)
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DownloadException : Error {
case responseDataMissing
case responseFailed
case requestMissing
case requestMissingPath
case requestMissingURL
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DecodableRequestBuilderError: Error {
case emptyDataResponse
case nilHTTPResponse
case jsonDecoding(DecodingError)
case generalError(Error)
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Response<T> {
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let statusCode: Int
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let header: [String: String]
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let body: T?
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(statusCode: Int, header: [String: String], body: T?) {
self.statusCode = statusCode
self.header = header
self.body = body
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} 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)
}
}

View File

@ -0,0 +1,44 @@
//
// OpenISO8601DateFormatter.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
// https://stackoverflow.com/a/50281094/976628
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class OpenISO8601DateFormatter: DateFormatter {
static let withoutSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
private func setup() {
calendar = Calendar(identifier: .iso8601)
locale = Locale(identifier: "en_US_POSIX")
timeZone = TimeZone(secondsFromGMT: 0)
dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
}
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func date(from string: String) -> Date? {
if let result = super.date(from: string) {
return result
}
return OpenISO8601DateFormatter.withoutSeconds.date(from: string)
}
}

View File

@ -0,0 +1,40 @@
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "{{projectName}}",
platforms: [
.iOS(.v9),
.macOS(.v10_11),
.tvOS(.v9),
.watchOS(.v3)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "{{projectName}}",
targets: ["{{projectName}}"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
{{#useAlamofire}}
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1"),
{{/useAlamofire}}
{{#usePromiseKit}}
.package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.12.0"),
{{/usePromiseKit}}
{{#useRxSwift}}
.package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0"),
{{/useRxSwift}}
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "{{projectName}}",
dependencies: [{{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}],
path: "{{projectName}}/Classes"
),
]
)

View File

@ -0,0 +1,38 @@
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.watchos.deployment_target = '3.0'
s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}{{/podVersion}}'
s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}' }{{/podSource}}
{{#podAuthors}}
s.authors = '{{podAuthors}}'
{{/podAuthors}}
{{#podSocialMediaURL}}
s.social_media_url = '{{podSocialMediaURL}}'
{{/podSocialMediaURL}}
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', '~> 6.12.0'
{{/usePromiseKit}}
{{#useRxSwift}}
s.dependency 'RxSwift', '~> 5.0.0'
{{/useRxSwift}}
{{#useAlamofire}}
s.dependency 'Alamofire', '~> 4.9.1'
{{/useAlamofire}}
end

View File

@ -0,0 +1,69 @@
# Swift5 API client for {{{projectName}}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec from a remote server, you can easily generate an API client.
- API version: {{appVersion}}
- Package version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
## Installation
### Carthage
Run `carthage update`
### CocoaPods
Run `pod install`
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization
{{^authMethods}} All endpoints do not require authorization.
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}## {{{name}}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{{keyParamName}}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{{flow}}}
- **Authorization URL**: {{{authorizationUrl}}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - **{{{scope}}}**: {{{description}}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -0,0 +1,36 @@
// SynchronizedDictionary.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
internal 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
)
internal 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
}
}
}
}

View File

@ -0,0 +1,17 @@
name: {{projectName}}
targets:
{{projectName}}:
type: framework
platform: iOS
deploymentTarget: "10.0"
sources: [{{projectName}}]
info:
path: ./Info.plist
version: {{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}{{/podVersion}}
settings:
APPLICATION_EXTENSION_API_ONLY: true
scheme: {}
{{#useAlamofire}}dependencies:{{/useAlamofire}}{{^useAlamofire}}{{#useRxSwift}}dependencies:{{/useRxSwift}}{{/useAlamofire}}{{^useAlamofire}}{{^useRxSwift}}{{#usePromiseKit}}dependencies:{{/usePromiseKit}}{{/useRxSwift}}{{/useAlamofire}}{{#useAlamofire}}
- carthage: Alamofire{{/useAlamofire}}{{#useRxSwift}}
- carthage: RxSwift{{/useRxSwift}}{{#usePromiseKit}}
- carthage: PromiseKit{{/usePromiseKit}}

View File

@ -0,0 +1 @@
"{{baseName}}": {{paramName}}{{^required}}?{{/required}}.encodeToJSON()

View File

@ -0,0 +1,252 @@
{{#operations}}//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
import RxSwift{{/useRxSwift}}{{#useCombine}}
import Combine{{/useCombine}}
{{#swiftUseApiNamespace}}
extension {{projectName}}API {
{{/swiftUseApiNamespace}}
{{#description}}
/** {{description}} */{{/description}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}} {
{{#operation}}
{{#allParams}}
{{#isEnum}}
/**
* enum for parameter {{paramName}}
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, CaseIterable {
{{#allowableValues}}
{{#enumVars}}
case {{name}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/allParams}}
{{^usePromiseKit}}
{{^useRxSwift}}
{{^useResult}}
{{^useCombine}}
/**
{{#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 apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?,_ error: Error?) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in
switch result {
{{#returnType}}
case let .success(response):
completion(response.body, nil)
{{/returnType}}
{{^returnType}}
case .success:
completion((), nil)
{{/returnType}}
case let .failure(error):
completion(nil, error)
}
}
}
{{/useCombine}}
{{/useResult}}
{{/useRxSwift}}
{{/usePromiseKit}}
{{#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}}
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending()
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in
switch result {
{{#returnType}}
case let .success(response):
deferred.resolver.fulfill(response.body!)
{{/returnType}}
{{^returnType}}
case .success:
deferred.resolver.fulfill(())
{{/returnType}}
case let .failure(error):
deferred.resolver.reject(error)
}
}
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}}
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
return Observable.create { observer -> Disposable in
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in
switch result {
{{#returnType}}
case let .success(response):
observer.onNext(response.body!)
{{/returnType}}
{{^returnType}}
case .success:
observer.onNext(())
{{/returnType}}
case let .failure(error):
observer.onError(error)
}
observer.onCompleted()
}
return Disposables.create()
}
}
{{/useRxSwift}}
{{#useCombine}}
/**
{{#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 apiResponseQueue: The queue on which api response is dispatched.
- returns: AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>
*/
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> {
return Future<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>.init { promisse in
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in
switch result {
{{#returnType}}
case let .success(response):
promisse(.success(response.body!))
{{/returnType}}
{{^returnType}}
case .success:
promisse(.success(()))
{{/returnType}}
case let .failure(error):
promisse(.failure(error))
}
}
}.eraseToAnyPublisher()
}
{{/useCombine}}
{{#useResult}}
/**
{{#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 apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the result
*/
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}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in
switch result {
{{#returnType}}
case let .success(response):
completion(.success(response.body!))
{{/returnType}}
{{^returnType}}
case .success:
completion(.success(()))
{{/returnType}}
case let .failure(error):
completion(.failure(error))
}
}
}
{{/useResult}}
/**
{{#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}}
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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 = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/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 = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}})
{{/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([{{^queryParams}}:{{/queryParams}}
{{#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.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}}
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

@ -0,0 +1,97 @@
# {{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{{basePath}}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
# **{{{operationId}}}**
```swift
{{^usePromiseKit}}
{{^useRxSwift}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)
{{/useRxSwift}}
{{/usePromiseKit}}
{{#usePromiseKit}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
{{/usePromiseKit}}
{{#useRxSwift}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
{{/useRxSwift}}
```
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
### Example
```swift
// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new
import {{{projectName}}}
{{#allParams}}let {{paramName}} = {{{vendorExtensions.x-swift-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/allParams}}
{{^usePromiseKit}}
{{^useRxSwift}}
{{#summary}}
// {{{.}}}
{{/summary}}
{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { (response, error) in
guard error == nil else {
print(error)
return
}
if (response) {
dump(response)
}
}
{{/useRxSwift}}
{{/usePromiseKit}}
{{#usePromiseKit}}
{{#summary}}
// {{{.}}}
{{/summary}}
{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).then {
// when the promise is fulfilled
}.always {
// regardless of whether the promise is fulfilled, or rejected
}.catch { errorType in
// when the promise is rejected
}
{{/usePromiseKit}}
{{#useRxSwift}}
// TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new
{{/useRxSwift}}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}Void (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
{{/operation}}
{{/operations}}

View File

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

View File

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

View File

@ -0,0 +1,378 @@
// AlamofireImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import Alamofire
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type {
return AlamofireRequestBuilder<T>.self
}
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type {
return AlamofireDecodableRequestBuilder<T>.self
}
}
// Store manager to retain its reference
private var managerStore = SynchronizedDictionary<String, Alamofire.SessionManager>()
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers)
}
/**
May be overridden by a subclass if you want to control the session
configuration.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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 custom request constructor.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest() -> URLRequest? {
let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding()
guard let originalRequest = try? URLRequest(url: URLString, method: HTTPMethod(rawValue: method)!, headers: buildHeaders()) else { return nil }
return try? encoding.encode(originalRequest, with: parameters)
}
/**
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.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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).
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest {
return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers)
}
override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, Error>) -> Void) {
let managerId:String = UUID().uuidString
// Create a new manager for each request to customize its request header
let manager = createSessionManager()
managerStore[managerId] = manager
let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding()
let xMethod = Alamofire.HTTPMethod(rawValue: method)
let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL }
.map { $0.0 }
if fileKeys.count > 0 {
manager.upload(multipartFormData: { mpForm in
for (k, v) in self.parameters! {
switch v {
case let fileURL as URL:
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, apiResponseQueue, completion)
case .failure(let encodingError):
apiResponseQueue.async{
completion(.failure(ErrorResponse.error(415, nil, encodingError)))
}
}
})
} else {
let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request: request, managerId, apiResponseQueue, completion)
}
}
fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, Error>) -> 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(queue: apiResponseQueue, completionHandler: { (stringResponse) in
cleanupRequest()
switch stringResponse.result {
case let .success(value):
completion(.success(Response(response: stringResponse.response!, body: value as? T)))
case let .failure(error):
completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, error)))
}
})
case is URL.Type:
validatedRequest.responseData(queue: apiResponseQueue, 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(.success(Response(response: dataResponse.response!, body: filePath as? T)))
} catch let requestParserError as DownloadException {
completion(.failure(ErrorResponse.error(400, dataResponse.data, requestParserError)))
} catch let error {
completion(.failure(ErrorResponse.error(400, dataResponse.data, error)))
}
return
})
case is Void.Type:
validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { (voidResponse) in
cleanupRequest()
switch voidResponse.result {
case .success:
completion(.success(Response(response: voidResponse.response!, body: nil)))
case let .failure(error):
completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, error)))
}
})
default:
validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { (dataResponse) in
cleanupRequest()
switch dataResponse.result {
case .success:
completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T)))
case let .failure(error):
completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, error)))
}
})
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} 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
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireDecodableRequestBuilder<T:Decodable>: AlamofireRequestBuilder<T> {
override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, Error>) -> 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(queue: apiResponseQueue, completionHandler: { (stringResponse) in
cleanupRequest()
switch stringResponse.result {
case let .success(value):
completion(.success(Response(response: stringResponse.response!, body: value as? T)))
case let .failure(error):
completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, error)))
}
})
case is Void.Type:
validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { (voidResponse) in
cleanupRequest()
switch voidResponse.result {
case .success:
completion(.success(Response(response: voidResponse.response!, body: nil)))
case let .failure(error):
completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, error)))
}
})
case is Data.Type:
validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { (dataResponse) in
cleanupRequest()
switch dataResponse.result {
case .success:
completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T)))
case let .failure(error):
completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, error)))
}
})
default:
validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { (dataResponse: DataResponse<Data>) in
cleanupRequest()
guard dataResponse.result.isSuccess else {
completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)))
return
}
guard let data = dataResponse.data, !data.isEmpty else {
completion(.failure(ErrorResponse.error(-1, nil, DecodableRequestBuilderError.emptyDataResponse)))
return
}
guard let httpResponse = dataResponse.response else {
completion(.failure(ErrorResponse.error(-2, nil, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
let decodeResult = CodableHelper.decode(T.self, from: data)
switch decodeResult {
case let .success(decodableObj):
completion(.success(Response(response: httpResponse, body: decodableObj)))
case let .failure(error):
completion(.failure(error))
}
})
}
}
}
extension JSONDataEncoding: ParameterEncoding {
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply. This should have a single key/value
/// pair with "jsonData" as the key and a Data object as the value.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
let urlRequest = try urlRequest.asURLRequest()
return self.encode(urlRequest, with: parameters)
}
}

View File

@ -0,0 +1,544 @@
// URLSessionImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if !os(macOS)
import MobileCoreServices
#endif
class URLSessionRequestBuilderFactory: RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type {
return URLSessionRequestBuilder<T>.self
}
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type {
return URLSessionDecodableRequestBuilder<T>.self
}
}
// Store the URLSession to retain its reference
private var urlSessionStore = SynchronizedDictionary<String, URLSession>()
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionRequestBuilder<T>: RequestBuilder<T> {
let progress = Progress()
private var observation: NSKeyValueObservation?
deinit {
observation?.invalidate()
}
fileprivate let sessionDelegate = SessionDelegate()
/**
May be assigned if you want to control the authentication challenges.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/**
May be assigned if you want to do any of those things:
- control the task completion
- intercept and handle errors like authorization
- retry the request.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)?
required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) {
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers)
}
/**
May be overridden by a subclass if you want to control the URLSession
configuration.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLSession() -> URLSession {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = buildHeaders()
sessionDelegate.credential = credential
sessionDelegate.taskDidReceiveChallenge = taskDidReceiveChallenge
return URLSession(configuration: configuration, delegate: sessionDelegate, delegateQueue: nil)
}
/**
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.
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func contentTypeForFormPart(fileURL: URL) -> String? {
return nil
}
/**
May be overridden by a subclass if you want to control the URLRequest
configuration (e.g. to override the cache policy).
*/
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) throws -> URLRequest {
guard let url = URL(string: URLString) else {
throw DownloadException.requestMissingURL
}
var originalRequest = URLRequest(url: url)
originalRequest.httpMethod = method.rawValue
buildHeaders().forEach { key, value in
originalRequest.setValue(value, forHTTPHeaderField: key)
}
headers.forEach { key, value in
originalRequest.setValue(value, forHTTPHeaderField: key)
}
let modifiedRequest = try encoding.encode(originalRequest, with: parameters)
return modifiedRequest
}
override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Result<Response<T>, Error>) -> Void) {
let urlSessionId:String = UUID().uuidString
// Create a new manager for each request to customize its request header
let urlSession = createURLSession()
urlSessionStore[urlSessionId] = urlSession
let parameters: [String: Any] = self.parameters ?? [:]
let fileKeys = parameters.filter { $1 is NSURL }
.map { $0.0 }
let encoding: ParameterEncoding
if fileKeys.count > 0 {
encoding = FileUploadEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:))
} else if isBody {
encoding = JSONDataEncoding()
} else {
encoding = URLEncoding()
}
guard let xMethod = HTTPMethod(rawValue: method) else {
fatalError("Unsuported Http method - \(method)")
}
let cleanupRequest = {
urlSessionStore[urlSessionId] = nil
self.observation?.invalidate()
}
do {
let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers)
let dataTask = urlSession.dataTask(with: request) { [weak self] data, response, error in
guard let self = self else { return }
if let taskCompletionShouldRetry = self.taskCompletionShouldRetry {
taskCompletionShouldRetry(data, response, error) { [weak self] shouldRetry in
guard let self = self else { return }
if shouldRetry {
cleanupRequest()
self.execute(apiResponseQueue, completion)
} else {
apiResponseQueue.async {
self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion)
}
}
}
} else {
apiResponseQueue.async {
self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion)
}
}
}
if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) {
observation = dataTask.progress.observe(\.fractionCompleted) { newProgress, _ in
self.progress.totalUnitCount = newProgress.totalUnitCount
self.progress.completedUnitCount = newProgress.completedUnitCount
}
onProgressReady?(progress)
}
dataTask.resume()
} catch {
apiResponseQueue.async {
cleanupRequest()
completion(.failure(ErrorResponse.error(415, nil, error)))
}
}
}
fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Result<Response<T>, Error>) -> Void) {
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, nil, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
switch T.self {
case is String.Type:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
completion(.success(Response<T>(response: httpResponse, body: body as? T)))
case is URL.Type:
do {
guard error == nil else {
throw DownloadException.responseFailed
}
guard let data = data else {
throw DownloadException.responseDataMissing
}
let fileManager = FileManager.default
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let requestURL = try self.getURL(from: urlRequest)
var requestPath = try self.getPath(from: requestURL)
if let headerFileName = self.getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) {
requestPath = requestPath.appending("/\(headerFileName)")
}
let filePath = documentsDirectory.appendingPathComponent(requestPath)
let directoryPath = filePath.deletingLastPathComponent().path
try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
try data.write(to: filePath, options: .atomic)
completion(.success(Response(response: httpResponse, body: filePath as? T)))
} catch let requestParserError as DownloadException {
completion(.failure(ErrorResponse.error(400, data, requestParserError)))
} catch let error {
completion(.failure(ErrorResponse.error(400, data, error)))
}
case is Void.Type:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
completion(.success(Response(response: httpResponse, body: nil)))
default:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
completion(.success(Response(response: httpResponse, body: data as? T)))
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func buildHeaders() -> [String: String] {
var httpHeaders = {{projectName}}API.customHeaders
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
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionDecodableRequestBuilder<T:Decodable>: URLSessionRequestBuilder<T> {
override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Result<Response<T>, Error>) -> Void) {
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, nil, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
switch T.self {
case is String.Type:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
completion(.success(Response<T>(response: httpResponse, body: body as? T)))
case is Void.Type:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
completion(.success(Response(response: httpResponse, body: nil)))
case is Data.Type:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
completion(.success(Response(response: httpResponse, body: data as? T)))
default:
if let error = error {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, error)))
return
}
guard let data = data, !data.isEmpty else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, DecodableRequestBuilderError.emptyDataResponse)))
return
}
let decodeResult = CodableHelper.decode(T.self, from: data)
switch decodeResult {
case let .success(decodableObj):
completion(.success(Response(response: httpResponse, body: decodableObj)))
case let .failure(error):
completion(.failure(error))
}
}
}
}
fileprivate class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate {
var credential: URLCredential?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest
}
fileprivate class URLEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String : Any]?) throws -> URLRequest {
var urlRequest = urlRequest
guard let parameters = parameters else { return urlRequest }
guard let url = urlRequest.url else {
throw DownloadException.requestMissingURL
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters)
urlRequest.url = urlComponents.url
}
return urlRequest
}
}
fileprivate class FileUploadEncoding: ParameterEncoding {
let contentTypeForFormPart: (_ fileURL: URL) -> String?
init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) {
self.contentTypeForFormPart = contentTypeForFormPart
}
func encode(_ urlRequest: URLRequest, with parameters: [String : Any]?) throws -> URLRequest {
var urlRequest = urlRequest
for (k, v) in parameters ?? [:] {
switch v {
case let fileURL as URL:
let fileData = try Data(contentsOf: fileURL)
let mimetype = self.contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL)
urlRequest = configureFileUploadRequest(urlRequest: urlRequest, name: fileURL.lastPathComponent, data: fileData, mimeType: mimetype)
case let string as String:
if let data = string.data(using: .utf8) {
urlRequest = configureFileUploadRequest(urlRequest: urlRequest, name: k, data: data, mimeType: nil)
}
case let number as NSNumber:
if let data = number.stringValue.data(using: .utf8) {
urlRequest = configureFileUploadRequest(urlRequest: urlRequest, name: k, data: data, mimeType: nil)
}
default:
fatalError("Unprocessable value \(v) with key \(k)")
}
}
return urlRequest
}
private func configureFileUploadRequest(urlRequest: URLRequest, name: String, data: Data, mimeType: String?) -> URLRequest {
var urlRequest = urlRequest
var body = urlRequest.httpBody ?? Data()
// https://stackoverflow.com/a/26163136/976628
let boundary = "Boundary-\(UUID().uuidString)"
urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(name)\"\r\n")
if let mimeType = mimeType {
body.append("Content-Type: \(mimeType)\r\n\r\n")
}
body.append(data)
body.append("\r\n")
body.append("--\(boundary)--\r\n")
urlRequest.httpBody = body
return urlRequest
}
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
}
fileprivate extension Data {
/// Append string to NSMutableData
///
/// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to NSData, and then add that data to the NSMutableData, this wraps it in a nice convenient little extension to NSMutableData. This converts using UTF-8.
///
/// - parameter string: The string to be added to the `NSMutableData`.
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
extension JSONDataEncoding: ParameterEncoding {}

View File

@ -0,0 +1,24 @@
{{#models}}{{#model}}//
// {{classname}}.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
{{#description}}
/** {{description}} */{{/description}}
{{#isArrayModel}}
{{> modelArray}}
{{/isArrayModel}}
{{^isArrayModel}}
{{#isEnum}}
{{> modelEnum}}
{{/isEnum}}
{{^isEnum}}
{{> modelObject}}
{{/isEnum}}
{{/isArrayModel}}
{{/model}}
{{/models}}

View File

@ -0,0 +1 @@
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{parent}}

View File

@ -0,0 +1,7 @@
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, Codable, CaseIterable {
{{#allowableValues}}
{{#enumVars}}
case {{name}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -0,0 +1,7 @@
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, Codable, CaseIterable {
{{#allowableValues}}
{{#enumVars}}
case {{name}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -0,0 +1,84 @@
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable {
{{#allVars}}
{{#isEnum}}
{{> modelInlineEnumDeclaration}}
{{/isEnum}}
{{/allVars}}
{{#allVars}}
{{#isEnum}}
{{#description}}/** {{description}} */
{{/description}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{/isEnum}}
{{^isEnum}}
{{#description}}/** {{description}} */
{{/description}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}: {{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{#objcCompatible}}
{{#vendorExtensions.x-swift-optional-scalar}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}Num: NSNumber? {
get {
return {{name}}.map({ return NSNumber(value: $0) })
}
}
{{/vendorExtensions.x-swift-optional-scalar}}
{{/objcCompatible}}
{{/isEnum}}
{{/allVars}}
{{#hasVars}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allVars}}) {
{{#allVars}}
self.{{name}} = {{name}}
{{/allVars}}
}
{{/hasVars}}
{{#additionalPropertiesType}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var additionalProperties: [String:{{{additionalPropertiesType}}}] = [:]
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? {
get {
if let value = additionalProperties[key] {
return value
}
return nil
}
set {
additionalProperties[key] = newValue
}
}
// Encodable protocol methods
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
{{#allVars}}
try container.encode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{name}}}, forKey: "{{{baseName}}}")
{{/allVars}}
try container.encodeMap(additionalProperties)
}
// Decodable protocol methods
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
{{#allVars}}
{{name}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: "{{{baseName}}}")
{{/allVars}}
var nonAdditionalPropertyKeys = Set<String>()
{{#allVars}}
nonAdditionalPropertyKeys.insert("{{{baseName}}}")
{{/allVars}}
additionalProperties = try container.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys)
}
{{/additionalPropertiesType}}
{{^additionalPropertiesType}}{{#vendorExtensions.x-codegen-has-escaped-property-names}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: String, CodingKey, CaseIterable { {{#allVars}}
case {{name}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}}{{/allVars}}
}
{{/vendorExtensions.x-codegen-has-escaped-property-names}}{{/additionalPropertiesType}}
}

View File

@ -0,0 +1,11 @@
{{#models}}{{#model}}# {{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isContainer}}[**{{dataType}}**]({{complexType}}.md){{/isContainer}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{{/model}}{{/models}}

View File

@ -0,0 +1,89 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.options;
import com.google.common.collect.ImmutableMap;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.languages.Swift5Codegen;
import java.util.Map;
public class Swift5OptionsProvider 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 NON_PUBLIC_API_REQUIRED_VALUE = "false";
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_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";
public static final String LIBRARY_VALUE = "alamofire";
@Override
public String getLanguage() {
return "swift5";
}
@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(Swift5Codegen.PROJECT_NAME, PROJECT_NAME_VALUE)
.put(Swift5Codegen.RESPONSE_AS, RESPONSE_AS_VALUE)
.put(CodegenConstants.NON_PUBLIC_API, NON_PUBLIC_API_REQUIRED_VALUE)
.put(Swift5Codegen.OBJC_COMPATIBLE, OBJC_COMPATIBLE_VALUE)
.put(Swift5Codegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_VALUE)
.put(Swift5Codegen.POD_SOURCE, POD_SOURCE_VALUE)
.put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE)
.put(Swift5Codegen.POD_AUTHORS, POD_AUTHORS_VALUE)
.put(Swift5Codegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE)
.put(Swift5Codegen.POD_LICENSE, POD_LICENSE_VALUE)
.put(Swift5Codegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE)
.put(Swift5Codegen.POD_SUMMARY, POD_SUMMARY_VALUE)
.put(Swift5Codegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE)
.put(Swift5Codegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE)
.put(Swift5Codegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE)
.put(Swift5Codegen.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.LIBRARY, LIBRARY_VALUE)
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -0,0 +1,147 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift5;
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.Swift5Codegen;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Swift5CodegenTest {
Swift5Codegen swiftCodegen = new Swift5Codegen();
@Test(enabled = true)
public void testCapitalizedReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as");
}
@Test(enabled = true)
public void testReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public");
}
@Test(enabled = true)
public void shouldNotBreakNonReservedWord() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error");
}
@Test(enabled = true)
public void shouldNotBreakCorrectName() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName");
}
@Test(enabled = true)
public void testSingleWordAllCaps() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value");
}
@Test(enabled = true)
public void testSingleWordLowercase() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value");
}
@Test(enabled = true)
public void testCapitalsWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName");
}
@Test(enabled = true)
public void testCapitalsWithDash() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName");
}
@Test(enabled = true)
public void testCapitalsWithSpace() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName");
}
@Test(enabled = true)
public void testLowercaseWithUnderscore() throws Exception {
Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName");
}
@Test(enabled = true)
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 Data when response format is binary", enabled = true)
public void binaryDataTest() {
// TODO update json file
final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/2_0/binaryDataTest.json");
final DefaultCodegen codegen = new Swift5Codegen();
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, "URL");
Assert.assertEquals(op.bodyParam.dataType, "URL");
Assert.assertTrue(op.bodyParam.isBinary);
Assert.assertTrue(op.responses.get(0).isBinary);
}
@Test(description = "returns Date when response format is date", enabled = true)
public void dateTest() {
final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/2_0/datePropertyTest.json");
final DefaultCodegen codegen = new Swift5Codegen();
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, "Date");
Assert.assertEquals(op.bodyParam.dataType, "Date");
}
@Test(enabled = true)
public void testDefaultPodAuthors() throws Exception {
// Given
// When
swiftCodegen.processOpts();
// Then
final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift5Codegen.POD_AUTHORS);
Assert.assertEquals(podAuthors, Swift5Codegen.DEFAULT_POD_AUTHORS);
}
@Test(enabled = true)
public void testPodAuthors() throws Exception {
// Given
final String openAPIDevs = "OpenAPI Devs";
swiftCodegen.additionalProperties().put(Swift5Codegen.POD_AUTHORS, openAPIDevs);
// When
swiftCodegen.processOpts();
// Then
final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift5Codegen.POD_AUTHORS);
Assert.assertEquals(podAuthors, openAPIDevs);
}
}

View File

@ -0,0 +1,133 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift5;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
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.Swift5Codegen;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.math.BigDecimal;
import java.util.Arrays;
@SuppressWarnings("static-method")
public class Swift5ModelEnumTest {
@Test(description = "convert a java model with an string enum and a default value")
public void convertStringDefaultValueTest() {
final StringSchema enumSchema = new StringSchema();
enumSchema.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3"));
enumSchema.setDefault("VALUE2");
final Schema model = new Schema().type("object").addProperties("name", enumSchema);
final DefaultCodegen codegen = new Swift5Codegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty enumVar = cm.vars.get(0);
Assert.assertEquals(enumVar.baseName, "name");
Assert.assertEquals(enumVar.dataType, "String");
Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, ".value2");
Assert.assertEquals(enumVar.baseType, "String");
Assert.assertTrue(enumVar.isEnum);
}
@Test(description = "convert a java model with an reserved word string enum and a default value")
public void convertReservedWordStringDefaultValueTest() {
final StringSchema enumSchema = new StringSchema();
enumSchema.setEnum(Arrays.asList("1st", "2nd", "3rd"));
enumSchema.setDefault("2nd");
final Schema model = new Schema().type("object").addProperties("name", enumSchema);
final DefaultCodegen codegen = new Swift5Codegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty enumVar = cm.vars.get(0);
Assert.assertEquals(enumVar.baseName, "name");
Assert.assertEquals(enumVar.dataType, "String");
Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, "._2nd");
Assert.assertEquals(enumVar.baseType, "String");
Assert.assertTrue(enumVar.isEnum);
}
@Test(description = "convert a java model with an integer enum and a default value")
public void convertIntegerDefaultValueTest() {
final IntegerSchema enumSchema = new IntegerSchema();
enumSchema.setEnum(Arrays.asList(1, 2, 3));
enumSchema.setDefault(2);
final Schema model = new Schema().type("object").addProperties("name", enumSchema);
final DefaultCodegen codegen = new Swift5Codegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty enumVar = cm.vars.get(0);
Assert.assertEquals(enumVar.baseName, "name");
Assert.assertEquals(enumVar.dataType, "Int");
Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, "._2");
Assert.assertEquals(enumVar.baseType, "Int");
Assert.assertTrue(enumVar.isEnum);
}
@Test(description = "convert a java model with an number enum and a default value")
public void convertNumberDefaultValueTest() {
final NumberSchema enumSchema = new NumberSchema();
enumSchema.setEnum(Arrays.asList(new BigDecimal(10), new BigDecimal(100), new BigDecimal(1000)));
enumSchema.setDefault(new BigDecimal((100)));
final Schema model = new Schema().type("object").addProperties("name", enumSchema);
final DefaultCodegen codegen = new Swift5Codegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty enumVar = cm.vars.get(0);
Assert.assertEquals(enumVar.baseName, "name");
Assert.assertEquals(enumVar.dataType, "Double");
Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, "._100");
Assert.assertEquals(enumVar.baseType, "Double");
Assert.assertTrue(enumVar.isEnum);
}
}

View File

@ -0,0 +1,132 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.swift5;
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.Swift5Codegen;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class Swift5ModelTest {
@Test(description = "convert a simple java model", enabled = true)
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 Swift5Codegen();
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, "Date");
Assert.assertEquals(property7.name, "dateOfBirth");
Assert.assertNull(property7.defaultValue);
Assert.assertEquals(property7.baseType, "Date");
Assert.assertFalse(property7.hasMore);
Assert.assertFalse(property7.required);
Assert.assertFalse(property7.isContainer);
}
}

View File

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

View File

@ -0,0 +1,466 @@
{
"swagger": "2.0",
"info": {
"title": "Swift 5 Test Schema",
"description": "This is a test schema which exercises Swagger schema features for testing the swift5 language codegen module.",
"termsOfService": "These are the dummy Terms of Service for the swift5 test schema.",
"contact": {
"name": "John Doe",
"url": "http://www.example.com",
"email": "jdoe@example.com"
},
"license": {
"name": "This is the license name for the swift5 test schema.",
"url": "http://www.example.com"
},
"version": "1.0"
},
"host": "api.example.com",
"basePath": "/basePath",
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
{
"name": "Swift5Test"
}
],
"externalDocs": {
"description": "Look in this doc for further information.",
"url": "https://www.example.com/doc/index.html"
},
"paths": {
"/allModels": {
"get": {
"tags": [
"Swift5Test"
],
"summary": "Get all of the models",
"description": "This endpoint tests get a dictionary which contains examples of all of the models.",
"operationId": "GetAllModels",
"produces": [
"application/json"
],
"parameters": [
{
"name": "client_id",
"in": "query",
"description": "id that represent the Api client",
"required": true,
"type": "string",
"x-example": "swagger_ui"
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/GetAllModelsResult"
}
},
"400": {
"description": "Invalid client input",
"schema": {
"$ref": "#/definitions/ErrorInfo"
}
},
"424": {
"description": "Timeout",
"schema": {
"$ref": "#/definitions/ErrorInfo"
}
},
"500": {
"description": "Unexpected Server Error",
"schema": {
"$ref": "#/definitions/ErrorInfo"
}
}
}
}
}
},
"definitions": {
"StringEnum": {
"type": "string",
"enum": [
"stringEnumValue1",
"stringEnumValue2",
"stringEnumValue3"
]
},
"AllPrimitives": {
"type": "object",
"properties": {
"myInteger": {
"type": "integer"
},
"myIntegerArray": {
"type": "array",
"items": {
"type": "integer"
}
},
"myLong": {
"type": "integer",
"format": "int64"
},
"myLongArray": {
"type": "array",
"items": {
"type": "integer",
"format": "int64"
}
},
"myFloat": {
"type": "number",
"format": "float"
},
"myFloatArray": {
"type": "array",
"items": {
"type": "number",
"format": "float"
}
},
"myDouble": {
"type": "number",
"format": "double"
},
"myDoubleArray": {
"type": "array",
"items": {
"type": "number",
"format": "double"
}
},
"myString": {
"type": "string"
},
"myStringArray": {
"type": "array",
"items": {
"type": "string"
}
},
"myBytes": {
"type": "string",
"format": "byte"
},
"myBytesArray": {
"type": "array",
"items": {
"type": "string",
"format": "byte"
}
},
"myBoolean": {
"type": "boolean"
},
"myBooleanArray": {
"type": "array",
"items": {
"type": "boolean"
}
},
"myDate": {
"type": "string",
"format": "date"
},
"myDateArray": {
"type": "array",
"items": {
"type": "string",
"format": "date"
}
},
"myDateTime": {
"type": "string",
"format": "date-time"
},
"myDateTimeArray": {
"type": "array",
"items": {
"type": "string",
"format": "date-time"
}
},
"myFile": {
"type": "file"
},
"myFileArray": {
"type": "array",
"items": {
"type": "file"
}
},
"myUUID": {
"type": "string",
"format": "uuid"
},
"myUUIDArray": {
"type": "array",
"items": {
"type": "string",
"format": "uuid"
}
},
"myStringEnum": {
"$ref": "#/definitions/StringEnum"
},
"myStringEnumArray": {
"type": "array",
"items": {
"$ref": "#/definitions/StringEnum"
}
},
"myInlineStringEnum": {
"type": "string",
"enum": [
"inlineStringEnumValue1",
"inlineStringEnumValue2",
"inlineStringEnumValue3"
]
}
},
"description": "Object which contains lots of different primitive OpenAPI types"
},
"ErrorInfo": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"details": {
"type": "array",
"items": {
"type": "string"
}
}
},
"description": "Example Error object"
},
"ModelStringArray": {
"type": "array",
"description": "This defines an array of strings.",
"items": {
"type": "string"
}
},
"ModelDoubleArray": {
"type": "array",
"description": "This defines an array of doubles.",
"items": {
"type": "number",
"format": "double"
}
},
"ModelErrorInfoArray": {
"type": "array",
"description": "This defines an array of ErrorInfo objects.",
"items": {
"$ref": "#/definitions/ErrorInfo"
}
},
"VariableNameTest": {
"description": "This object contains property names which we know will be different from their variable name. Examples of this include snake case property names and property names which are Swift 5 reserved words.",
"type": "object",
"properties": {
"example_name": {
"description": "This snake-case examle_name property name should be converted to a camelCase variable name like exampleName",
"type": "string"
},
"for": {
"description": "This property name is a reserved word in most languages, including Swift 5.",
"type": "string"
},
"normalName": {
"description": "This model object property name should be unchanged from the JSON property name.",
"type": "string"
}
}
},
"GetAllModelsResult": {
"type": "object",
"properties": {
"myPrimitiveArray": {
"type": "array",
"items": {
"$ref": "#/definitions/AllPrimitives"
}
},
"myPrimitive": {
"$ref": "#/definitions/AllPrimitives"
},
"myVariableNameTest": {
"$ref": "#/definitions/VariableNameTest"
}
},
"description": "Response object containing AllPrimitives object"
},
"ModelWithStringAdditionalPropertiesOnly": {
"description": "This is an empty model with no properties and only additionalProperties of type string",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"ModelWithIntAdditionalPropertiesOnly": {
"description": "This is an empty model with no properties and only additionalProperties of type int32",
"type": "object",
"additionalProperties": {
"type": "integer",
"format": "int32"
}
},
"ModelWithPropertiesAndAdditionalProperties": {
"description": "This is an empty model with no properties and only additionalProperties of type int32",
"type": "object",
"required": [
"myIntegerReq",
"myPrimitiveReq",
"myStringArrayReq",
"myPrimitiveArrayReq"
],
"properties": {
"myIntegerReq": {
"type": "integer"
},
"myIntegerOpt": {
"type": "integer"
},
"myPrimitiveReq": {
"$ref": "#/definitions/AllPrimitives"
},
"myPrimitiveOpt": {
"$ref": "#/definitions/AllPrimitives"
},
"myStringArrayReq": {
"type": "array",
"items": {
"type": "string"
}
},
"myStringArrayOpt": {
"type": "array",
"items": {
"type": "string"
}
},
"myPrimitiveArrayReq": {
"type": "array",
"items": {
"$ref": "#/definitions/AllPrimitives"
}
},
"myPrimitiveArrayOpt": {
"type": "array",
"items": {
"$ref": "#/definitions/AllPrimitives"
}
}
},
"additionalProperties": {
"type": "string"
}
},
"SampleBase": {
"type": "object",
"description": "This is a base class object from which other classes will derive.",
"properties": {
"baseClassStringProp": {
"type": "string"
},
"baseClassIntegerProp": {
"type": "integer",
"format": "int32"
}
}
},
"SampleSubClass": {
"description": "This is a subclass defived from the SampleBase class.",
"allOf": [
{
"$ref": "#/definitions/SampleBase"
},
{
"type": "object",
"properties": {
"subClassStringProp": {
"type": "string"
},
"subClassIntegerProp": {
"type": "integer",
"format": "int32"
}
}
}
]
},
"BaseCard": {
"type": "object",
"description": "This is a base card object which uses a 'cardType' discriminator.",
"x-unit-tests": ["B45"],
"discriminator": "cardType",
"required": [
"cardType"
],
"properties": {
"cardType": {
"type": "string"
}
}
},
"PersonCard": {
"description": "This is a card object for a Person derived from BaseCard.",
"x-unit-tests": ["B45"],
"allOf": [
{
"$ref": "#/definitions/BaseCard"
},
{
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
}
}
]
},
"PlaceCard": {
"description": "This is a card object for a Person derived from BaseCard.",
"x-unit-tests": ["B45"],
"allOf": [
{
"$ref": "#/definitions/BaseCard"
},
{
"type": "object",
"properties": {
"placeName": {
"type": "string"
},
"placeAddress": {
"type": "string"
}
}
}
]
}
}
}

View File

@ -1310,6 +1310,9 @@
</property>
</activation>
<modules>
<module>samples/client/petstore/swift5/default/SwaggerClientTests</module>
<module>samples/client/petstore/swift5/promisekit/SwaggerClientTests</module>
<module>samples/client/petstore/swift5/rxswift/SwaggerClientTests</module>
<module>samples/client/petstore/swift4/default/SwaggerClientTests</module>
<module>samples/client/petstore/swift4/promisekit/SwaggerClientTests</module>
<module>samples/client/petstore/swift4/rxswift/SwaggerClientTests</module>

View File

@ -38,7 +38,7 @@ public class RequestBuilder<T> {
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((NSProgress) -> ())?
public var onProgressReady: ((NSProgress) -> Void)?
required public init(method: String, URLString: String, parameters: [String: AnyObject]?, isBody: Bool, headers: [String: String] = [:]) {
self.method = method
@ -74,4 +74,3 @@ public class RequestBuilder<T> {
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -7,8 +7,6 @@
import Alamofire
public class PetAPI: APIBase {
/**
Add a new pet to the store
@ -17,12 +15,11 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
addPetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Add a new pet to the store
- POST /pet - OAuth:
@ -52,12 +49,11 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Deletes a pet
- DELETE /pet/{petId} - OAuth:
@ -96,11 +92,10 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Finds Pets by status
- GET /pet/findByStatus
@ -188,11 +183,10 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Finds Pets by tags
- GET /pet/findByTags
@ -280,11 +274,10 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Find pet by ID
- GET /pet/{petId}
@ -373,12 +366,11 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
updatePetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Update an existing pet
- PUT /pet - OAuth:
@ -409,12 +401,11 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
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:
@ -454,12 +445,11 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage - OAuth:

View File

@ -7,8 +7,6 @@
import Alamofire
public class StoreAPI: APIBase {
/**
Delete purchase order by ID
@ -17,12 +15,11 @@ public class StoreAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Delete purchase order by ID
- DELETE /store/order/{orderId}
@ -53,11 +50,10 @@ public class StoreAPI: APIBase {
*/
public class func getInventory(completion: ((data: [String: Int32]?, error: ErrorType?) -> Void)) {
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
completion(data: response?.body, error: error)
}
}
/**
Returns pet inventories by status
- GET /store/inventory
@ -90,11 +86,10 @@ public class StoreAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Find purchase order by ID
- GET /store/order/{orderId}
@ -156,11 +151,10 @@ public class StoreAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Place an order for a pet
- POST /store/order - examples: [{contentType=application/json, example={

View File

@ -7,8 +7,6 @@
import Alamofire
public class UserAPI: APIBase {
/**
Create user
@ -17,12 +15,11 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
createUserWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Create user
- POST /user
@ -49,12 +46,11 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
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)
@ -80,12 +76,11 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
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)
@ -111,12 +106,11 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Delete user
- DELETE /user/{username}
@ -148,11 +142,10 @@ public class UserAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Get user by user name
- GET /user/{username} - examples: [{contentType=application/json, example={
@ -222,11 +215,10 @@ public class UserAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
/**
Logs user into the system
- GET /user/login - parameter username: (query) The user name for login (optional)
@ -258,12 +250,11 @@ public class UserAPI: APIBase {
- parameter completion: completion handler to receive the data and the error objects
*/
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
completion(error: error);
logoutUserWithRequestBuilder().execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Logs out current logged in user session
- GET /user/logout
@ -292,12 +283,11 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
updateUserWithRequestBuilder(username: username, user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
/**
Updated user
- PUT /user/{username}

View File

@ -114,7 +114,7 @@ public final class ISOFullDate: CustomStringConvertible {
[
.Year,
.Month,
.Day,
.Day
],
fromDate: date
)
@ -175,5 +175,3 @@ extension ISOFullDate: JSONEncodable {
return "\(year)-\(month)-\(day)"
}
}

View File

@ -37,7 +37,7 @@ public class Response<T> {
private var once = dispatch_once_t()
class Decoders {
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static private var decoders = [String: ((AnyObject) -] AnyObject)>()
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
let key = "\(T.self)"
@ -61,10 +61,10 @@ class Decoders {
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;
return source.intValue as! T
}
if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T;
return source.longLongValue as! T
}
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
@ -164,7 +164,6 @@ class Decoders {
return instance
}
// Decoder for [Order]
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
return Decoders.decode(clazz: [Order].self, source: source)
@ -182,7 +181,6 @@ class Decoders {
return instance
}
// Decoder for [Pet]
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
return Decoders.decode(clazz: [Pet].self, source: source)
@ -200,7 +198,6 @@ class Decoders {
return instance
}
// Decoder for [Tag]
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
return Decoders.decode(clazz: [Tag].self, source: source)
@ -214,7 +211,6 @@ class Decoders {
return instance
}
// Decoder for [User]
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
return Decoders.decode(clazz: [User].self, source: source)

View File

@ -7,7 +7,6 @@
import Foundation
public class Category: JSONEncodable {
public var id: Int64?
public var name: String?

View File

@ -7,7 +7,6 @@
import Foundation
public class Order: JSONEncodable {
public enum Status: String {
case Placed = "placed"

View File

@ -7,7 +7,6 @@
import Foundation
public class Pet: JSONEncodable {
public enum Status: String {
case Available = "available"

View File

@ -7,7 +7,6 @@
import Foundation
public class Tag: JSONEncodable {
public var id: Int64?
public var name: String?

View File

@ -7,7 +7,6 @@
import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?

View File

@ -13,7 +13,6 @@ 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
@ -41,6 +40,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

View File

@ -20,6 +20,4 @@ class ViewController: UIViewController {
// Dispose of any resources that can be recreated.
}
}

View File

@ -27,7 +27,7 @@ final class ISOFullDateTests: XCTestCase {
[
.Year,
.Month,
.Day,
.Day
],
fromDate: date
)
@ -62,7 +62,7 @@ final class ISOFullDateTests: XCTestCase {
[
.Year,
.Month,
.Day,
.Day
],
fromDate: date
)

View File

@ -94,7 +94,7 @@ class StoreAPITests: XCTestCase {
progressExpectation.fulfill()
}
requestBuilder.execute { (response, error) in
requestBuilder.execute { (_, _) in
responseExpectation.fulfill()
}

View File

@ -38,7 +38,7 @@ public class RequestBuilder<T> {
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((NSProgress) -> ())?
public var onProgressReady: ((NSProgress) -> Void)?
required public init(method: String, URLString: String, parameters: [String: AnyObject]?, isBody: Bool, headers: [String: String] = [:]) {
self.method = method
@ -74,4 +74,3 @@ public class RequestBuilder<T> {
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -8,8 +8,6 @@
import Alamofire
import PromiseKit
public class PetAPI: APIBase {
/**
Add a new pet to the store
@ -18,8 +16,8 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
addPetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -70,8 +68,8 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -132,7 +130,7 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -241,7 +239,7 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -350,7 +348,7 @@ public class PetAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -460,8 +458,8 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
updatePetWithRequestBuilder(pet: pet).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -513,8 +511,8 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -577,8 +575,8 @@ public class PetAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (_, error) -> Void in
completion(error: error)
}
}

View File

@ -8,8 +8,6 @@
import Alamofire
import PromiseKit
public class StoreAPI: APIBase {
/**
Delete purchase order by ID
@ -18,8 +16,8 @@ public class StoreAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -71,7 +69,7 @@ public class StoreAPI: APIBase {
*/
public class func getInventory(completion: ((data: [String: Int32]?, error: ErrorType?) -> Void)) {
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
completion(data: response?.body, error: error)
}
}
@ -82,7 +80,7 @@ public class StoreAPI: APIBase {
*/
public class func getInventory() -> Promise<[String: Int32]> {
let deferred = Promise<[String: Int32]>.pendingPromise()
getInventory() { data, error in
getInventory { data, error in
if let error = error {
deferred.reject(error)
} else {
@ -124,7 +122,7 @@ public class StoreAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -207,7 +205,7 @@ public class StoreAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}

View File

@ -8,8 +8,6 @@
import Alamofire
import PromiseKit
public class UserAPI: APIBase {
/**
Create user
@ -18,8 +16,8 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
createUserWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -67,8 +65,8 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
createUsersWithArrayInputWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -115,8 +113,8 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
createUsersWithListInputWithRequestBuilder(user: user).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -163,8 +161,8 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in
completion(error: error)
}
}
@ -217,7 +215,7 @@ public class UserAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -308,7 +306,7 @@ public class UserAPI: APIBase {
*/
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);
completion(data: response?.body, error: error)
}
}
@ -362,8 +360,8 @@ public class UserAPI: APIBase {
- parameter completion: completion handler to receive the data and the error objects
*/
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
completion(error: error);
logoutUserWithRequestBuilder().execute { (_, error) -> Void in
completion(error: error)
}
}
@ -374,7 +372,7 @@ public class UserAPI: APIBase {
*/
public class func logoutUser() -> Promise<Void> {
let deferred = Promise<Void>.pendingPromise()
logoutUser() { error in
logoutUser { error in
if let error = error {
deferred.reject(error)
} else {
@ -412,8 +410,8 @@ public class UserAPI: APIBase {
- 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 { (response, error) -> Void in
completion(error: error);
updateUserWithRequestBuilder(username: username, user: user).execute { (_, error) -> Void in
completion(error: error)
}
}

View File

@ -115,7 +115,7 @@ public final class ISOFullDate: CustomStringConvertible {
[
.Year,
.Month,
.Day,
.Day
],
fromDate: date
)

View File

@ -37,7 +37,7 @@ public class Response<T> {
private var once = dispatch_once_t()
class Decoders {
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static private var decoders = [String: ((AnyObject) -] AnyObject)>()
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
let key = "\(T.self)"
@ -61,10 +61,10 @@ class Decoders {
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;
return source.intValue as! T
}
if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T;
return source.longLongValue as! T
}
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
@ -164,7 +164,6 @@ class Decoders {
return instance
}
// Decoder for [Order]
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
return Decoders.decode(clazz: [Order].self, source: source)
@ -182,7 +181,6 @@ class Decoders {
return instance
}
// Decoder for [Pet]
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
return Decoders.decode(clazz: [Pet].self, source: source)
@ -200,7 +198,6 @@ class Decoders {
return instance
}
// Decoder for [Tag]
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
return Decoders.decode(clazz: [Tag].self, source: source)
@ -214,7 +211,6 @@ class Decoders {
return instance
}
// Decoder for [User]
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
return Decoders.decode(clazz: [User].self, source: source)

View File

@ -7,7 +7,6 @@
import Foundation
public class Category: JSONEncodable {
public var id: Int64?
public var name: String?

View File

@ -7,7 +7,6 @@
import Foundation
public class Order: JSONEncodable {
public enum Status: String {
case Placed = "placed"

View File

@ -7,7 +7,6 @@
import Foundation
public class Pet: JSONEncodable {
public enum Status: String {
case Available = "available"

View File

@ -7,7 +7,6 @@
import Foundation
public class Tag: JSONEncodable {
public var id: Int64?
public var name: String?

View File

@ -7,7 +7,6 @@
import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?

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