remove unused templates, pass x-codegen-acceptable-status-codes to api method template

This commit is contained in:
Ivan Smolin 2022-03-02 17:13:47 +03:00
parent cb6dbc9d6a
commit e320bb3826
14 changed files with 53 additions and 1249 deletions

View File

@ -8,6 +8,7 @@ import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.slf4j.Logger;
@ -26,10 +27,8 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
public static final String PROJECT_NAME = "projectName";
public static final String RESPONSE_AS = "responseAs";
public static final String UNWRAP_REQUIRED = "unwrapRequired";
public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
protected String projectName = "SwaggerClient";
protected String projectName = "SwaggerAPI";
private boolean unwrapRequired;
protected boolean swiftUseApiNamespace;
private String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "Swaggers";
@ -68,7 +67,6 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift");
apiPackage = File.separator + "APIs";
modelPackage = File.separator + "Models";
languageSpecificPrimitives = new HashSet<>(
Arrays.asList(
@ -100,9 +98,6 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
);
reservedWords = new HashSet<>(
Arrays.asList(
// name used by swift client
"ErrorResponse", "Response",
//
// Swift keywords. This list is taken from here:
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
@ -181,9 +176,6 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
"Treat 'required' properties in response as non-optional "
+ "(which would crash the app if api returns null as opposed "
+ "to required option specified in json schema"));
cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE,
"Flag to make all the API classes inner-class "
+ "of {{projectName}}API"));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
.defaultValue(Boolean.TRUE.toString()));
@ -227,45 +219,11 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
}
additionalProperties.put(RESPONSE_AS, responseAs);
// Setup swiftUseApiNamespace option, which makes all the API
// classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
supportingFiles.add(new SupportingFile("APIHelper.mustache",
sourceFolder,
"APIHelper.swift"));
supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache",
sourceFolder,
"AlamofireImplementations.swift"));
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder,
"Configuration.swift"));
supportingFiles.add(new SupportingFile("Extensions.mustache",
sourceFolder,
"Extensions.swift"));
supportingFiles.add(new SupportingFile("Models.mustache",
sourceFolder,
"Models.swift"));
supportingFiles.add(new SupportingFile("APIs.mustache",
sourceFolder,
"APIs.swift"));
supportingFiles.add(new SupportingFile("CodableHelper.mustache",
sourceFolder,
"CodableHelper.swift"));
supportingFiles.add(new SupportingFile("JSONEncodableEncoding.mustache",
sourceFolder,
"JSONEncodableEncoding.swift"));
supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache",
sourceFolder,
"JSONEncodingHelper.swift"));
supportingFiles.add(new SupportingFile("JSONValue.mustache",
sourceFolder,
"JSONValue.swift"));
supportingFiles.add(new SupportingFile("Servers.mustache",
sourceFolder,
projectName + "+Servers.swift"));
copyFistAllOfProperties = true;
}
@Override
@ -329,6 +287,13 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
return toModelName(type);
}
@Override
public CodegenParameter fromRequestBody(RequestBody body, String name, Schema schema, Map<String, Schema> schemas, Set<String> imports) {
CodegenParameter codegenParameter = super.fromRequestBody(body, name, schema, schemas, imports);
codegenParameter.description = codegenParameter.description == null ? schema.getDescription() : codegenParameter.description;
return codegenParameter;
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("URL");
@ -532,6 +497,24 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
codegenOperation.returnType = null;
}
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
for (CodegenContent content : codegenOperation.getContents()) {
ArrayList<String> contentStatusCodes = new ArrayList<>();
for (CodegenResponse codegenResponse : codegenOperation.responses) {
Schema schema = (Schema) codegenResponse.getSchema();
String responseContentType = (String) schema.getExtensions().get("x-content-type");
if (Objects.equals(responseContentType, content.getContentType())) {
contentStatusCodes.add(codegenResponse.code);
}
}
content.getContentExtensions()
.put("x-codegen-acceptable-status-codes", String.join(", ", contentStatusCodes));
}
}
return codegenOperation;
}
@ -547,10 +530,6 @@ public class TINetworkingCodegen extends DefaultCodegenConfig {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
return String.valueOf(value);

View File

@ -1,65 +0,0 @@
// APIHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct APIHelper {
public 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
}
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?> {
result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",")
} else if let value: Any = item.value {
result[item.key] = "\(value)"
}
}
}
public 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
}
})
}
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?> {
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

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

View File

@ -1,422 +0,0 @@
// AlamofireImplementations.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
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: [String: Alamofire.SessionManager] = [:]
// Sync queue to manage safe access to the store manager
private let syncQueue = DispatchQueue(label: "thread-safe-sync-queue", attributes: .concurrent)
open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
required public 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.
*/
open func createSessionManager() -> Alamofire.SessionManager {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = buildHeaders()
return Alamofire.SessionManager(configuration: configuration)
}
/**
May be overridden by a subclass if you want to control the Content-Type
that is given to an uploaded form part.
Return nil to use the default behavior (inferring the Content-Type from
the file extension). Return the desired Content-Type otherwise.
*/
open func contentTypeForFormPart(fileURL: URL) -> String? {
return nil
}
/**
May be overridden by a subclass if you want to control the request
configuration (e.g. to override the cache policy).
*/
open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest {
return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers)
}
override open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
let managerId:String = UUID().uuidString
// Create a new manager for each request to customize its request header
let manager = createSessionManager()
syncQueue.async(flags: .barrier) {
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, completion)
case .failure(let encodingError):
completion(nil, 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, completion)
}
}
fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
syncQueue.async(flags: .barrier) {
_ = managerStore.removeValue(forKey: managerId)
}
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
Response(
response: stringResponse.response!,
body: ((stringResponse.result.value ?? "") as! T)
),
nil
)
})
case is URL.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
do {
guard !dataResponse.result.isFailure else {
throw DownloadException.responseFailed
}
guard let data = dataResponse.data else {
throw DownloadException.responseDataMissing
}
guard let request = request.request else {
throw DownloadException.requestMissing
}
let fileManager = FileManager.default
let urlRequest = try request.asURLRequest()
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let requestURL = try self.getURL(from: urlRequest)
var requestPath = try self.getPath(from: requestURL)
if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) {
requestPath = requestPath.appending("/\(headerFileName)")
}
let filePath = documentsDirectory.appendingPathComponent(requestPath)
let directoryPath = filePath.deletingLastPathComponent().path
try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
try data.write(to: filePath, options: .atomic)
completion(
Response(
response: dataResponse.response!,
body: (filePath as! T)
),
nil
)
} catch let requestParserError as DownloadException {
completion(nil, ErrorResponse.error(400, dataResponse.data, requestParserError))
} catch let error {
completion(nil, ErrorResponse.error(400, dataResponse.data, error))
}
return
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
Response(
response: voidResponse.response!,
body: nil),
nil
)
})
default:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if dataResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
Response(
response: dataResponse.response!,
body: (dataResponse.data as! T)
),
nil
)
})
}
}
open func buildHeaders() -> [String: String] {
var httpHeaders = SessionManager.defaultHTTPHeaders
for (key, value) in self.headers {
httpHeaders[key] = value
}
return httpHeaders
}
fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? {
guard let contentDisposition = contentDisposition else {
return nil
}
let items = contentDisposition.components(separatedBy: ";")
var filename : String? = nil
for contentItem in items {
let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else {
break
}
filename = contentItem
return filename?
.replacingCharacters(in: range, with:"")
.replacingOccurrences(of: "\"", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
return filename
}
fileprivate func getPath(from url : URL) throws -> String {
guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else {
throw DownloadException.requestMissingPath
}
if path.hasPrefix("/") {
path.remove(at: path.startIndex)
}
return path
}
fileprivate func getURL(from urlRequest : URLRequest) throws -> URL {
guard let url = urlRequest.url else {
throw DownloadException.requestMissingURL
}
return url
}
}
fileprivate enum DownloadException : Error {
case responseDataMissing
case responseFailed
case requestMissing
case requestMissingPath
case requestMissingURL
}
public enum AlamofireDecodableRequestBuilderError: Error {
case emptyDataResponse
case nilHTTPResponse
case jsonDecoding(DecodingError)
case generalError(Error)
}
open class AlamofireDecodableRequestBuilder<T:Decodable>: AlamofireRequestBuilder<T> {
override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
let cleanupRequest = {
syncQueue.async(flags: .barrier) {
_ = managerStore.removeValue(forKey: managerId)
}
}
let validatedRequest = request.validate()
switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
Response(
response: stringResponse.response!,
body: ((stringResponse.result.value ?? "") as! T)
),
nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
Response(
response: voidResponse.response!,
body: nil),
nil
)
})
case is Data.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if dataResponse.result.isFailure {
completion(
nil,
ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
completion(
Response(
response: dataResponse.response!,
body: (dataResponse.data as! T)
),
nil
)
})
default:
validatedRequest.responseData(completionHandler: { (dataResponse: DataResponse<Data>) in
cleanupRequest()
guard dataResponse.result.isSuccess else {
completion(nil, ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!))
return
}
guard let data = dataResponse.data, !data.isEmpty else {
completion(nil, ErrorResponse.error(-1, nil, AlamofireDecodableRequestBuilderError.emptyDataResponse))
return
}
guard let httpResponse = dataResponse.response else {
completion(nil, ErrorResponse.error(-2, nil, AlamofireDecodableRequestBuilderError.nilHTTPResponse))
return
}
var responseObj: Response<T>? = nil
let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data)
if decodeResult.error == nil {
responseObj = Response(response: httpResponse, body: decodeResult.decodableObj)
}
completion(responseObj, decodeResult.error)
})
}
}
}

View File

@ -1,93 +0,0 @@
//
// CodableHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public typealias EncodeResult = (data: Data?, error: Error?)
enum DateError: String, Error {
case invalidDate
}
open class CodableHelper {
public static var dateformatter: DateFormatter?
open class func decode<T>(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable {
var returnedDecodable: T? = nil
var returnedError: Error? = nil
let decoder = JSONDecoder()
if let df = self.dateformatter {
decoder.dateDecodingStrategy = .formatted(df)
} else {
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
let container = try decoder.singleValueContainer()
let dateStr = try container.decode(String.self)
let formatters = [
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd HH:mm:ss"
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = format
return formatter
}
for formatter in formatters {
if let date = formatter.date(from: dateStr) {
return date
}
}
throw DateError.invalidDate
})
}
do {
returnedDecodable = try decoder.decode(type, from: data)
} catch {
returnedError = error
}
return (returnedDecodable, returnedError)
}
open class func encode<T>(_ value: T, prettyPrint: Bool = false) -> EncodeResult where T : Encodable {
var returnedData: Data?
var returnedError: Error? = nil
let encoder = JSONEncoder()
if prettyPrint {
encoder.outputFormatting = .prettyPrinted
}
encoder.dataEncodingStrategy = .base64
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:ss.SSSXXXXX"
encoder.dateEncodingStrategy = .formatted(formatter)
do {
returnedData = try encoder.encode(value)
} catch {
returnedError = error
}
return (returnedData, returnedError)
}
}

View File

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

View File

@ -1,186 +0,0 @@
// Extensions.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
import Alamofire{{#usePromiseKit}}
import PromiseKit{{/usePromiseKit}}
extension Bool: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Float: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int32) }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> Any { return NSNumber(value: self as Int64) }
}
extension Double: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
extension String: JSONEncodable {
func encodeToJSON() -> Any { return self as Any }
}
private func encodeIfPossible<T>(_ object: T) -> Any {
if let encodableObject = object as? JSONEncodable {
return encodableObject.encodeToJSON()
} else {
return object as Any
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> Any {
return self.map(encodeIfPossible)
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> Any {
var dictionary = [AnyHashable: Any]()
for (key, value) in self {
dictionary[key] = encodeIfPossible(value)
}
return dictionary as Any
}
}
extension Data: JSONEncodable {
func encodeToJSON() -> Any {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
private let dateFormatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateFormat = Configuration.dateFormat
fmt.locale = Locale(identifier: "en_US_POSIX")
return fmt
}()
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return dateFormatter.string(from: self) as Any
}
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any {
return self.uuidString
}
}
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 {
public mutating func encodeArray<T>(_ values: [T], forKey key: Self.Key) throws where T : Encodable {
var arrayContainer = nestedUnkeyedContainer(forKey: key)
try arrayContainer.encode(contentsOf: values)
}
public mutating func encodeArrayIfPresent<T>(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable {
if let values = values {
try encodeArray(values, forKey: key)
}
}
public mutating func encodeMap<T>(_ pairs: [Self.Key: T]) throws where T : Encodable {
for (key, value) in pairs {
try encode(value, forKey: key)
}
}
public mutating func encodeMapIfPresent<T>(_ pairs: [Self.Key: T]?) throws where T : Encodable {
if let pairs = pairs {
try encodeMap(pairs)
}
}
}
extension KeyedDecodingContainerProtocol {
public 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
}
public 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
}
public 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 {
public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pending()
self.execute { (response: Response<T>?, error: Error?) in
if let response = response {
deferred.fulfill(response)
} else {
deferred.reject(error!)
}
}
return deferred.promise
}
}{{/usePromiseKit}}

View File

@ -1,54 +0,0 @@
//
// JSONDataEncoding.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
import Alamofire
public struct JSONDataEncoding: ParameterEncoding {
// 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.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
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
}
public static func encodingParameters(jsonData: Data?) -> Parameters? {
var returnedParams: Parameters? = nil
if let jsonData = jsonData, !jsonData.isEmpty {
var params = Parameters()
params[jsonDataKey] = jsonData
returnedParams = params
}
return returnedParams
}
}

View File

@ -1,43 +0,0 @@
//
// JSONEncodingHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
import Alamofire
open class JSONEncodingHelper {
open class func encodingParameters<T:Encodable>(forEncodableObject encodableObj: T?) -> Parameters? {
var params: Parameters? = nil
// Encode the Encodable object
if let encodableObj = encodableObj {
let encodeResult = CodableHelper.encode(encodableObj, prettyPrint: true)
if encodeResult.error == nil {
params = JSONDataEncoding.encodingParameters(jsonData: encodeResult.data)
}
}
return params
}
open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? {
var params: Parameters? = nil
if let encodableObj = encodableObj {
do {
let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted)
params = JSONDataEncoding.encodingParameters(jsonData: data)
} catch {
print(error)
return nil
}
}
return params
}
}

View File

@ -1,99 +0,0 @@
//
// JSONEncodingHelper.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public enum JSONValue: Codable, Equatable {
case string(String)
case int(Int)
case double(Double)
case bool(Bool)
case object([String: JSONValue])
case array([JSONValue])
case null
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let string): try container.encode(string)
case .int(let int): try container.encode(int)
case .double(let double): try container.encode(double)
case .bool(let bool): try container.encode(bool)
case .object(let object): try container.encode(object)
case .array(let array): try container.encode(array)
case .null: try container.encode(Optional<String>.none)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = try ((try? container.decode(String.self)).map(JSONValue.string))
.or((try? container.decode(Int.self)).map(JSONValue.int))
.or((try? container.decode(Double.self)).map(JSONValue.double))
.or((try? container.decode(Bool.self)).map(JSONValue.bool))
.or((try? container.decode([String: JSONValue].self)).map(JSONValue.object))
.or((try? container.decode([JSONValue].self)).map(JSONValue.array))
.or((container.decodeNil() ? .some(JSONValue.null) : .none))
.resolve(
with: DecodingError.typeMismatch(
JSONValue.self,
DecodingError.Context(
codingPath: container.codingPath,
debugDescription: "Not a JSON value"
)
)
)
}
}
extension JSONValue: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension JSONValue: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = .int(value)
}
}
extension JSONValue: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = .double(value)
}
}
extension JSONValue: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension JSONValue: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, JSONValue)...) {
self = .object([String: JSONValue](uniqueKeysWithValues: elements))
}
}
extension JSONValue: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: JSONValue...) {
self = .array(elements)
}
}
fileprivate extension Optional {
func or(_ other: Optional) -> Optional {
switch self {
case .none: return other
case .some: return self
}
}
func resolve(with error: @autoclosure () -> Error) throws -> Wrapped {
switch self {
case .none: throw error()
case .some(let wrapped): return wrapped
}
}
}

View File

@ -1,65 +0,0 @@
# Swift5 API client for {{packageName}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## Overview
This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-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
Put the package under your project folder and add the following in import:
```
"./{{packageName}}"
```
## 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}}
{{#each scopes}} - **{{@key}}**: {{this}}
{{/each}}
{{/isOAuth}}
{{/authMethods}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -0,0 +1,13 @@
// {{projectName}}+Servers.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import TINetworking
public extension Server {
static var `default`: Server {
.init(baseUrl: "{{basePath}}")
}
}

View File

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

View File

@ -5,19 +5,15 @@
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
import Alamofire
{{#swiftUseApiNamespace}}
extension {{projectName}}API {
{{/swiftUseApiNamespace}}
import TINetworking
{{#description}}
/**
{{description}}
*/
{{/description}}
open class {{classname}} {
public extension EndpointRequest {
{{#operation}}
{{#contents}}
{{#parameters}}
@ -25,7 +21,7 @@ open class {{classname}} {
/**
* enum for parameter {{paramName}}
*/
public enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}}
enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}}
case {{name}} = {{#isContainer}}"{{/isContainer}}{{#isString}}"{{/isString}}{{{value}}}{{#isString}}"{{/isString}}{{#isContainer}}"{{/isContainer}}{{/enumVars}}{{/allowableValues}}
}
@ -37,97 +33,17 @@ open class {{classname}} {
{{/summary}}
{{#parameters}}
- 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}}
- parameter {{paramName}}: {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/parameters}}
- parameter completion: completion handler to receive the data and the error objects
*/
open class func {{operationId}}({{#parameters}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}{{#hasParams}}, {{/hasParams}}completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?,_ error: Error?) -> Void)) {
{{operationId}}WithRequestBuilder({{#parameters}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/parameters}}).execute { (response, error) -> Void in
{{#returnType}}
completion(response?.body, error)
{{/returnType}}
{{^returnType}}
if error == nil {
completion((), error)
} else {
completion(nil, error)
}
{{/returnType}}
}
}
/**
{{#summary}}
{{{summary}}}
{{/summary}}
- {{httpMethod}} {{{path}}}{{^notes}}
- {{{notes}}}{{/notes}}
{{#subresourceOperation}}
- subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}}
- defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}}
- {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}:
- type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}}
- name: {{name}}{{/authMethods}}{{#responseHeaders}}
- responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}}
- examples: {{{examples}}}{{/examples}}{{#externalDocs}}
- externalDocs: {{externalDocs}}{{/externalDocs}}
{{#parameters}}
- 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}}
{{/parameters}}
- returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}}
*/
open class func {{operationId}}WithRequestBuilder({{#parameters}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
{{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{{path}}}"{{#pathParams}}
let {{paramName}}PreEscape = "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})"
let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{{braces "left"}}{{baseName}}{{braces "right"}}", 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}}
{{#queryParams}}
{{#@first}}
var url = URLComponents(string: URLString)
url?.queryItems = APIHelper.mapValuesToQueryItems([
{{/@first}}
{{> _param}}{{#hasMore}}, {{/hasMore}}
{{#@last}}
])
{{/@last}}
{{/queryParams}}
{{^queryParams}}
let url = URLComponents(string: URLString)
{{/queryParams}}
{{#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}})
static func {{operationId}}({{#parameters}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}{{#hasParams}}, {{/hasParams}}server: Server = .default) -> EndpointRequest<{{#parameters}}{{{dataType}}}{{/parameters}}, {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
.init(templatePath: "{{{path}}}",
method: .init(rawValue: "{{httpMethod}}"),
body: body,
acceptableStatusCodes: [{{contentExtensions.x-codegen-acceptable-status-codes}}],
server: server)
}
{{/contents}}
{{/operation}}
}
{{#swiftUseApiNamespace}}
}
{{/swiftUseApiNamespace}}
{{/operations}}