Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[swift] Introduce result type #4511

Merged
merged 12 commits into from
Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bin/swift4-petstore-all.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

./bin/swift4-petstore.sh
./bin/swift4-petstore-promisekit.sh
./bin/swift4-petstore-result.sh
./bin/swift4-petstore-rxswift.sh
./bin/swift4-petstore-objcCompatible.sh
./bin/swift4-petstore-unwrapRequired.sh
Expand Down
7 changes: 7 additions & 0 deletions bin/swift4-petstore-result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "Result"
}
42 changes: 42 additions & 0 deletions bin/swift4-petstore-result.sh
Original file line number Diff line number Diff line change
@@ -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/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-result.json -o samples/client/petstore/swift4/resultLibrary --generate-alias-as-model $@"

java $JAVA_OPTS -jar $executable $ags

if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/resultLibrary
xcodegen generate
fi

if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/resultLibrary
swiftlint autocorrect
fi
2 changes: 1 addition & 1 deletion docs/generators/swift4.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ sidebar_label: swift4
|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 are available.| |null|
|responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result are available.| |null|
|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null|
|unwrapRequired|Treat 'required' properties in response as non-optional (which would crash the app if api returns null as opposed to required option specified in json schema| |null|
|objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
public static final String LENIENT_TYPE_CAST = "lenientTypeCast";
protected static final String LIBRARY_PROMISE_KIT = "PromiseKit";
protected static final String LIBRARY_RX_SWIFT = "RxSwift";
protected static final String[] RESPONSE_LIBRARIES = {LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT};
protected static final String LIBRARY_RESULT = "Result";
protected static final String[] RESPONSE_LIBRARIES = {LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT, LIBRARY_RESULT};
protected String projectName = "OpenAPIClient";
protected boolean nonPublicApi = false;
protected boolean unwrapRequired;
Expand Down Expand Up @@ -376,6 +377,9 @@ public void processOpts() {
if (ArrayUtils.contains(responseAs, LIBRARY_RX_SWIFT)) {
additionalProperties.put("useRxSwift", true);
}
if (ArrayUtils.contains(responseAs, LIBRARY_RESULT)) {
additionalProperties.put("useResult", true);
}

// Setup swiftUseApiNamespace option, which makes all the API
// classes inner-class of {{projectName}}API
Expand Down Expand Up @@ -429,6 +433,11 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache",
sourceFolder,
"JSONEncodingHelper.swift"));
if (ArrayUtils.contains(responseAs, LIBRARY_RESULT)) {
supportingFiles.add(new SupportingFile("Result.mustache",
sourceFolder,
"Result.swift"));
}
supportingFiles.add(new SupportingFile("git_push.sh.mustache",
"",
"git_push.sh"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
// https://openapi-generator.tech
//

import Foundation
import Alamofire{{#usePromiseKit}}
import Foundation{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}

extension Bool: JSONEncodable {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// Result.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//

import Foundation

#if swift(<5)

{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum Result<Value, Error: Swift.Error> {
case success(Value)
case failure(Error)
}

#endif
30 changes: 28 additions & 2 deletions modules/openapi-generator/src/main/resources/swift4/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
// https://openapi-generator.tech
//

import Foundation
import Alamofire{{#usePromiseKit}}
import Foundation{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
import RxSwift{{/useRxSwift}}

Expand Down Expand Up @@ -116,6 +115,33 @@ extension {{projectName}}API {
}
}
{{/useRxSwift}}
{{#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 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}}completion: @escaping ((_ result: Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in
if let error = error {
completion(.failure(error))
{{#returnType}}
} else if let response = response {
completion(.success(response.body!))
} else {
fatalError()
}
{{/returnType}}
{{^returnType}}
} else {
completion(.success(()))
}
{{/returnType}}
}
}
{{/useResult}}

/**
{{#summary}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public struct APIHelper {

public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] {
return source.reduce(into: [String: String]()) { (result, item) in
if let collection = item.value as? Array<Any?> {
if let collection = item.value as? [Any?] {
result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",")
} else if let value: Any = item.value {
result[item.key] = "\(value)"
Expand All @@ -46,15 +46,15 @@ public struct APIHelper {
}

public static func mapValueToPathItem(_ source: Any) -> Any {
if let collection = source as? Array<Any?> {
if let collection = source as? [Any?] {
return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",")
}
return source
}

public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? {
let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in
if let collection = item.value as? Array<Any?> {
if let collection = item.value as? [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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class AnotherFakeAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class FakeAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class FakeClassnameTags123API {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class PetAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class StoreAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

open class UserAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
//

import Foundation
import Alamofire

extension Bool: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class AnotherFakeAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class FakeAPI {
/**
Expand Down Expand Up @@ -379,13 +378,13 @@ internal class FakeAPI {
To test enum parameters

- parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional)
- parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .-efg)
- parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg)
- parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .-efg)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg)
- parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
- parameter enumQueryDouble: (query) Query parameter enum test (double) (optional)
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .$)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .-efg)
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg)
- parameter completion: completion handler to receive the data and the error objects
*/
internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
Expand All @@ -403,13 +402,13 @@ internal class FakeAPI {
- GET /fake
- To test enum parameters
- parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional)
- parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .-efg)
- parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg)
- parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .-efg)
- parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg)
- parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
- parameter enumQueryDouble: (query) Query parameter enum test (double) (optional)
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .$)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .-efg)
- parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar)
- parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg)
- returns: RequestBuilder<Void>
*/
internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder<Void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class FakeClassnameTags123API {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class PetAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class StoreAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//

import Foundation
import Alamofire

internal class UserAPI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
//

import Foundation
import Alamofire

extension Bool: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
Expand Down
16 changes: 8 additions & 8 deletions samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -453,13 +453,13 @@ To test enum parameters
import PetstoreClient

let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional)
let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .-efg)
let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg)
let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional)
let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .-efg)
let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg)
let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional)
let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional)
let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .$)
let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .-efg)
let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar)
let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg)

// To test enum parameters
FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) { (response, error) in
Expand All @@ -479,13 +479,13 @@ FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHea
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional]
**enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .-efg]
**enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg]
**enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional]
**enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .-efg]
**enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg]
**enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional]
**enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional]
**enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .$]
**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .-efg]
**enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar]
**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg]

### Return type

Expand Down
Loading