[swift] small improvements (#19675)

* [swift] small improments

* [swift] small improments

* [swift] small improments

* [swift] make CI pass

* [swift] make CI pass

* [swift] make CI pass

* [swift] make CI pass

* [swift] make CI pass

* [swift] make CI pass

* [swift] make CI pass
This commit is contained in:
Bruno Coelho 2024-09-27 06:11:08 +01:00 committed by GitHub
parent 76aca6618f
commit 911455d206
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1321 changed files with 1282 additions and 81137 deletions

View File

@ -1,4 +1,4 @@
name: Samples Swift name: Samples Swift 5
on: on:
push: push:
@ -16,24 +16,18 @@ jobs:
os: [macos-latest] os: [macos-latest]
sample: sample:
- samples/client/petstore/swift5/alamofireLibrary - samples/client/petstore/swift5/alamofireLibrary
- samples/client/petstore/swift5/anycodableLibrary
- samples/client/petstore/swift5/asyncAwaitLibrary - samples/client/petstore/swift5/asyncAwaitLibrary
- samples/client/petstore/swift5/combineLibrary - samples/client/petstore/swift5/combineLibrary
- samples/client/petstore/swift5/default - samples/client/petstore/swift5/default
- samples/client/petstore/swift5/deprecated
- samples/client/petstore/swift5/frozenEnums
- samples/client/petstore/swift5/nonPublicApi
- samples/client/petstore/swift5/objcCompatible - samples/client/petstore/swift5/objcCompatible
- samples/client/petstore/swift5/oneOf - samples/client/petstore/swift5/oneOf
- samples/client/petstore/swift5/promisekitLibrary - samples/client/petstore/swift5/promisekitLibrary
- samples/client/petstore/swift5/readonlyProperties
- samples/client/petstore/swift5/resultLibrary - samples/client/petstore/swift5/resultLibrary
- samples/client/petstore/swift5/rxswiftLibrary - samples/client/petstore/swift5/rxswiftLibrary
- samples/client/petstore/swift5/urlsessionLibrary - samples/client/petstore/swift5/urlsessionLibrary
- samples/client/petstore/swift5/validation - samples/client/petstore/swift5/validation
# NOTE: disabled as vaporLibrary doesnt build when adding this CI config # NOTE: disabled as vaporLibrary doesnt build when adding this CI config
#- samples/client/petstore/swift5/vaporLibrary #- samples/client/petstore/swift5/vaporLibrary
- samples/client/petstore/swift5/x-swift-hashable
include: include:
- os: ubuntu-latest - os: ubuntu-latest
sample: samples/client/petstore/swift5/alamofireLibrary sample: samples/client/petstore/swift5/alamofireLibrary

View File

@ -87,7 +87,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks | | | Languages/Frameworks |
| -------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | -------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, Spring 6 RestClient, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (9.x - 18.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** | | **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, Spring 6 RestClient, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), **Swift** (2.x, 3.x, 4.x, 5.x, 6.x), **Typescript** (AngularJS, Angular (9.x - 18.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** ([Flight](https://docs.flightphp.com/), Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), [Cask](https://github.com/com-lihaoyi/cask), Scalatra) | | **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** ([Flight](https://docs.flightphp.com/), Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), [Cask](https://github.com/com-lihaoyi/cask), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** | | **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) | | **Configuration files** | [**Apache2**](https://httpd.apache.org/) |

View File

@ -1,10 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/anycodableLibrary
inputSpec: modules/openapi-generator/src/test/resources/3_0/any_codable.yaml
modelNamePrefix: Prefix
modelNameSuffix: Suffix
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,10 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/deprecated
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-deprecated-fields.yaml
templateDir: modules/openapi-generator/src/main/resources/swift5
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,12 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/frozenEnums
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift5
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
sortParamsByRequiredFlag: false
enumUnknownDefaultCase: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,21 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/nonPublicApi
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift5
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
sortParamsByRequiredFlag: false
nonPublicApi: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType

View File

@ -1,11 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/readonlyProperties
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift5
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
readonlyProperties: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -7,5 +7,19 @@ additionalProperties:
responseAs: Result responseAs: Result
podAuthors: "" podAuthors: ""
podSummary: PetstoreClient podSummary: PetstoreClient
sortParamsByRequiredFlag: false
enumUnknownDefaultCase: true
nonPublicApi: true
readonlyProperties: true
hashableModels: false
projectName: PetstoreClient projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator podHomepage: https://github.com/openapitools/openapi-generator
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType

View File

@ -1,11 +0,0 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/x-swift-hashable
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift5
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator
hashableModels: false

View File

@ -1,10 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/anycodableLibrary
inputSpec: modules/openapi-generator/src/test/resources/3_0/any_codable.yaml
modelNamePrefix: Prefix
modelNameSuffix: Suffix
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,10 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/deprecated
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-deprecated-fields.yaml
templateDir: modules/openapi-generator/src/main/resources/swift6
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,12 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/frozenEnums
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift6
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
sortParamsByRequiredFlag: false
enumUnknownDefaultCase: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -1,21 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/nonPublicApi
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift6
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
sortParamsByRequiredFlag: false
nonPublicApi: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType

View File

@ -1,11 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/readonlyProperties
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift6
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
readonlyProperties: true
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@ -7,5 +7,19 @@ additionalProperties:
responseAs: Result responseAs: Result
podAuthors: "" podAuthors: ""
podSummary: PetstoreClient podSummary: PetstoreClient
sortParamsByRequiredFlag: false
enumUnknownDefaultCase: true
nonPublicApi: true
readonlyProperties: true
hashableModels: false
projectName: PetstoreClient projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator podHomepage: https://github.com/openapitools/openapi-generator
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
-type: dashType

View File

@ -1,11 +0,0 @@
generatorName: swift6
outputDir: samples/client/petstore/swift6/x-swift-hashable
inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/swift6
generateAliasAsModel: true
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator
hashableModels: false

View File

@ -112,7 +112,7 @@ extension NullEncodable: Codable where Wrapped: Codable {
} }
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
{{#useAlamofire}} {{#useAlamofire}}
private var request: Request? private var request: Request?

View File

@ -9,28 +9,18 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.lock()
defer { lock.unlock() }
queue.sync { return self.dictionary[key]
value = self.dictionary[key]
}
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.lock()
defer { lock.unlock() }
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }
}
} }

View File

@ -585,7 +585,7 @@ private class FormDataEncoding: ParameterEncoding {
func mimeType(for url: URL) -> String { func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
#if canImport(UniformTypeIdentifiers) #if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) { if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream" return utType.preferredMIMEType ?? "application/octet-stream"

View File

@ -128,7 +128,7 @@ extension NullEncodable: Codable where Wrapped: Codable {
}{{/useAlamofire}} }{{/useAlamofire}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
{{#useAlamofire}} {{#useAlamofire}}
private var request: Request? private var request: Request?

View File

@ -9,26 +9,16 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.withLock {
self.dictionary[key]
queue.sync {
value = self.dictionary[key]
} }
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.withLock {
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }

View File

@ -591,7 +591,7 @@ private class FormDataEncoding: ParameterEncoding {
func mimeType(for url: URL) -> String { func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
#if canImport(UniformTypeIdentifiers) #if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) { if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream" return utType.preferredMIMEType ?? "application/octet-stream"

View File

@ -112,7 +112,7 @@ open class Response<T> {
} }
public final class RequestTask { public final class RequestTask {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
private var request: Request? private var request: Request?
internal func set(request: Request) { internal func set(request: Request) {

View File

@ -9,28 +9,18 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.lock()
defer { lock.unlock() }
queue.sync { return self.dictionary[key]
value = self.dictionary[key]
}
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.lock()
defer { lock.unlock() }
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }
}
} }

View File

@ -1,100 +0,0 @@
# Created by https://www.toptal.com/developers/gitignore/api/xcode,swift
# Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift
### Swift ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
## Obj-C/Swift specific
*.hmap
## App packaging
*.ipa
*.dSYM.zip
*.dSYM
## 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/
# Package.pins
# Package.resolved
# *.xcodeproj
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm
.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/
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build/
# Accio dependency management
Dependencies/
.accio/
# 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://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output
# Code Injection
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
### Xcode ###
## Xcode 8 and earlier
### Xcode Patch ###
*.xcodeproj/*
!*.xcodeproj/project.pbxproj
!*.xcodeproj/xcshareddata/
!*.xcworkspace/contents.xcworkspacedata
/*.gcno
**/xcshareddata/WorkspaceSettings.xcsettings
# End of https://www.toptal.com/developers/gitignore/api/xcode,swift

View File

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

View File

@ -1,24 +0,0 @@
.gitignore
.swiftformat
Cartfile
Package.swift
PetstoreClient.podspec
PetstoreClient/Classes/OpenAPIs/APIHelper.swift
PetstoreClient/Classes/OpenAPIs/APIs.swift
PetstoreClient/Classes/OpenAPIs/APIs/PetsAPI.swift
PetstoreClient/Classes/OpenAPIs/CodableHelper.swift
PetstoreClient/Classes/OpenAPIs/Configuration.swift
PetstoreClient/Classes/OpenAPIs/Extensions.swift
PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift
PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift
PetstoreClient/Classes/OpenAPIs/Models.swift
PetstoreClient/Classes/OpenAPIs/Models/PrefixPetSuffix.swift
PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift
PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift
PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift
PetstoreClient/Classes/OpenAPIs/Validation.swift
README.md
docs/PetsAPI.md
docs/PrefixPetSuffix.md
git_push.sh
project.yml

View File

@ -1,45 +0,0 @@
# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/
#
# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md
#
# file options
# uncomment below to exclude files, folders
#--exclude path/to/test1.swift,Snapshots,Build
# format options
--allman false
--binarygrouping 4,8
--commas always
--comments indent
--decimalgrouping 3,6
--elseposition same-line
--empty void
--exponentcase lowercase
--exponentgrouping disabled
--fractiongrouping disabled
--header ignore
--hexgrouping 4,8
--hexliteralcase uppercase
--ifdef indent
--indent 4
--indentcase false
--importgrouping testable-bottom
--linebreaks lf
--maxwidth none
--octalgrouping 4,8
--operatorfunc spaced
--patternlet hoist
--ranges spaced
--self remove
--semicolons inline
--stripunusedargs always
--swiftversion 5.4
--trimwhitespace always
--wraparguments preserve
--wrapcollections preserve
# rules
--enable isEmpty

View File

@ -1 +0,0 @@
github "Flight-School/AnyCodable" ~> 0.6

View File

@ -1,15 +0,0 @@
Pod::Spec.new do |s|
s.name = 'OpenAPIClient'
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 = '1.0.0'
s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' }
s.authors = 'OpenAPI Generator'
s.license = 'Proprietary'
s.homepage = 'https://github.com/OpenAPITools/openapi-generator'
s.summary = 'OpenAPIClient Swift SDK'
s.source_files = 'OpenAPIClient/Classes/**/*.swift'
s.dependency 'AnyCodable-FlightSchool', '~> 0.6'
end

View File

@ -1,33 +0,0 @@
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "PetstoreClient",
platforms: [
.iOS(.v11),
.macOS(.v10_13),
.tvOS(.v11),
.watchOS(.v4),
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "PetstoreClient",
targets: ["PetstoreClient"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/Flight-School/AnyCodable", .upToNextMajor(from: "0.6.1")),
],
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: "PetstoreClient",
dependencies: ["AnyCodable", ],
path: "PetstoreClient/Classes"
),
]
)

View File

@ -1,15 +0,0 @@
Pod::Spec.new do |s|
s.name = 'PetstoreClient'
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.tvos.deployment_target = '11.0'
s.watchos.deployment_target = '4.0'
s.version = '1.0.0'
s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' }
s.authors = ''
s.license = 'Proprietary'
s.homepage = 'https://github.com/openapitools/openapi-generator'
s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/**/*.swift'
s.dependency 'AnyCodable-FlightSchool', '~> 0.6'
end

View File

@ -1,121 +0,0 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
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? [Any?] {
result[item.key] = collection
.compactMap { value in convertAnyToString(value) }
.joined(separator: ",")
} else if let value: Any = item.value {
result[item.key] = convertAnyToString(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 convertAnyToString(_ value: Any?) -> String? {
guard let value = value else { return nil }
if let value = value as? any RawRepresentable {
return "\(value.rawValue)"
} else {
return "\(value)"
}
}
public static func mapValueToPathItem(_ source: Any) -> Any {
if let collection = source as? [Any?] {
return collection
.compactMap { value in convertAnyToString(value) }
.joined(separator: ",")
} else if let value = source as? any RawRepresentable {
return "\(value.rawValue)"
}
return source
}
/// maps all values from source to query parameters
///
/// explode attribute is respected: collection values might be either joined or split up into separate key value pairs
public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? {
let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in
if let collection = item.value.wrappedValue as? [Any?] {
let collectionValues: [String] = collection.compactMap { value in convertAnyToString(value) }
if !item.value.isExplode {
result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ",")))
} else {
collectionValues
.forEach { value in
result.append(URLQueryItem(name: item.key, value: value))
}
}
} else if let value = item.value.wrappedValue {
result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
}
}
if destination.isEmpty {
return nil
}
return destination.sorted { $0.name < $1.name }
}
/// maps all values from source to query parameters
///
/// collection values are always exploded
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? [Any?] {
collection
.compactMap { value in convertAnyToString(value) }
.forEach { value in
result.append(URLQueryItem(name: item.key, value: value))
}
} else if let value = item.value {
result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
}
}
if destination.isEmpty {
return nil
}
return destination.sorted { $0.name < $1.name }
}
}

View File

@ -1,68 +0,0 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
open class PetstoreClientAPI {
public static var basePath = "http://localhost"
public static var customHeaders: [String: String] = [:]
public static var credential: URLCredential?
public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory()
public static var apiResponseQueue: DispatchQueue = .main
}
open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String: String]
public let parameters: [String: Any]?
public let method: String
public let URLString: String
public let requestTask: RequestTask = RequestTask()
public let requiresAuthentication: Bool
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((Progress) -> Void)?
required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.headers = headers
self.requiresAuthentication = requiresAuthentication
addHeaders(PetstoreClientAPI.customHeaders)
}
open func addHeaders(_ aHeaders: [String: String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
@discardableResult
open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) -> RequestTask {
return requestTask
}
public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
open func addCredential() -> Self {
credential = PetstoreClientAPI.credential
return self
}
}
public protocol RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type
}

View File

@ -1,99 +0,0 @@
//
// PetsAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class PetsAPI {
/**
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func petsGet(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: PrefixPetSuffix?, _ error: Error?) -> Void)) -> RequestTask {
return petsGetWithRequestBuilder().execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
- GET /pets
- returns: RequestBuilder<PrefixPetSuffix>
*/
open class func petsGetWithRequestBuilder() -> RequestBuilder<PrefixPetSuffix> {
let localVariablePath = "/pets"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<PrefixPetSuffix>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Info for a specific pet
- parameter petId: (path) The id of the pet to retrieve
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func showPetById(petId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: AnyCodable?, _ error: Error?) -> Void)) -> RequestTask {
return showPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Info for a specific pet
- GET /pets/{petId}
- parameter petId: (path) The id of the pet to retrieve
- returns: RequestBuilder<AnyCodable>
*/
open class func showPetByIdWithRequestBuilder(petId: String) -> RequestBuilder<AnyCodable> {
var localVariablePath = "/pets/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<AnyCodable>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
}

View File

@ -1,49 +0,0 @@
//
// CodableHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open 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
}()
public static var dateFormatter: DateFormatter {
get { return customDateFormatter ?? defaultDateFormatter }
set { customDateFormatter = newValue }
}
public static var jsonDecoder: JSONDecoder {
get { return customJSONDecoder ?? defaultJSONDecoder }
set { customJSONDecoder = newValue }
}
public static var jsonEncoder: JSONEncoder {
get { return customJSONEncoder ?? defaultJSONEncoder }
set { customJSONEncoder = newValue }
}
open class func decode<T>(_ type: T.Type, from data: Data) -> Swift.Result<T, Error> where T: Decodable {
return Swift.Result { try jsonDecoder.decode(type, from: data) }
}
open class func encode<T>(_ value: T) -> Swift.Result<Data, Error> where T: Encodable {
return Swift.Result { try jsonEncoder.encode(value) }
}
}

View File

@ -1,18 +0,0 @@
// Configuration.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
open class Configuration {
/// Configures the range of HTTP status codes that will result in a successful response
///
/// If a HTTP status code is outside of this range the response will be interpreted as failed.
public static var successfulStatusCodeRange: Range = 200..<300
}

View File

@ -1,236 +0,0 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
#if canImport(AnyCodable)
import AnyCodable
#endif
extension Bool: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Float: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Double: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Decimal: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension String: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension URL: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension RawRepresentable where RawValue: JSONEncodable {
func encodeToJSON() -> Any { return self.rawValue }
}
private func encodeIfPossible<T>(_ object: T) -> Any {
if let encodableObject = object as? JSONEncodable {
return encodableObject.encodeToJSON()
} else {
return object
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> Any {
return self.map(encodeIfPossible)
}
}
extension Set: JSONEncodable {
func encodeToJSON() -> Any {
return Array(self).encodeToJSON()
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> Any {
var dictionary = [AnyHashable: Any]()
for (key, value) in self {
dictionary[key] = encodeIfPossible(value)
}
return dictionary
}
}
extension Data: JSONEncodable {
func encodeToJSON() -> Any {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return CodableHelper.dateFormatter.string(from: self)
}
}
extension JSONEncodable where Self: Encodable {
func encodeToJSON() -> Any {
guard let data = try? CodableHelper.jsonEncoder.encode(self) else {
fatalError("Could not encode to json: \(self)")
}
return data.encodeToJSON()
}
}
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)
}
}
public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws {
let decimalNumber = NSDecimalNumber(decimal: value)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale(identifier: "en_US")
let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)"
try encode(formattedString, forKey: key)
}
public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws {
if let value = value {
try encode(value, forKey: key)
}
}
}
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]?
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
}
public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal {
let stringValue = try decode(String.self, forKey: key)
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? {
guard let stringValue = try decodeIfPresent(String.self, forKey: key) else {
return nil
}
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
}
extension HTTPURLResponse {
var isStatusCodeSuccessful: Bool {
return Configuration.successfulStatusCodeRange.contains(statusCode)
}
}

View File

@ -1,56 +0,0 @@
//
// JSONDataEncoding.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public 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.
public 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
}
public static func encodingParameters(jsonData: Data?) -> [String: Any]? {
var returnedParams: [String: Any]?
if let jsonData = jsonData, !jsonData.isEmpty {
var params: [String: Any] = [:]
params[jsonDataKey] = jsonData
returnedParams = params
}
return returnedParams
}
}

View File

@ -1,45 +0,0 @@
//
// JSONEncodingHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class JSONEncodingHelper {
open class func encodingParameters<T: Encodable>(forEncodableObject encodableObj: T?) -> [String: Any]? {
var params: [String: Any]?
// 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
}
open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? {
var params: [String: Any]?
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

@ -1,129 +0,0 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
protocol JSONEncodable {
func encodeToJSON() -> Any
}
/// An enum where the last case value can be used as a default catch-all.
protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable
where RawValue: Decodable, AllCases: BidirectionalCollection {}
extension CaseIterableDefaultsLast {
/// Initializes an enum such that if a known raw value is found, then it is decoded.
/// Otherwise the last case is used.
/// - Parameter decoder: A decoder.
public init(from decoder: Decoder) throws {
if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) {
self = value
} else if let lastValue = Self.allCases.last {
self = lastValue
} else {
throw DecodingError.valueNotFound(
Self.Type.self,
.init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast")
)
}
}
}
/// A flexible type that can be encoded (`.encodeNull` or `.encodeValue`)
/// or not encoded (`.encodeNothing`). Intended for request payloads.
public enum NullEncodable<Wrapped: Hashable>: Hashable {
case encodeNothing
case encodeNull
case encodeValue(Wrapped)
}
extension NullEncodable: Codable where Wrapped: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Wrapped.self) {
self = .encodeValue(value)
} else if container.decodeNil() {
self = .encodeNull
} else {
self = .encodeNothing
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .encodeNothing: return
case .encodeNull: try container.encodeNil()
case .encodeValue(let wrapped): try container.encode(wrapped)
}
}
}
public enum ErrorResponse: Error {
case error(Int, Data?, URLResponse?, Error)
}
public enum DownloadException: Error {
case responseDataMissing
case responseFailed
case requestMissing
case requestMissingPath
case requestMissingURL
}
public enum DecodableRequestBuilderError: Error {
case emptyDataResponse
case nilHTTPResponse
case unsuccessfulHTTPStatusCode
case jsonDecoding(DecodingError)
case generalError(Error)
}
open class Response<T> {
public let statusCode: Int
public let header: [String: String]
public let body: T
public let bodyData: Data?
public init(statusCode: Int, header: [String: String], body: T, bodyData: Data?) {
self.statusCode = statusCode
self.header = header
self.body = body
self.bodyData = bodyData
}
public convenience init(response: HTTPURLResponse, body: T, bodyData: Data?) {
let rawHeader = response.allHeaderFields
var responseHeader = [String: String]()
for (key, value) in rawHeader {
if let key = key.base as? String, let value = value as? String {
responseHeader[key] = value
}
}
self.init(statusCode: response.statusCode, header: responseHeader, body: body, bodyData: bodyData)
}
}
public final class RequestTask {
private var lock = NSRecursiveLock()
private var task: URLSessionDataTaskProtocol?
internal func set(task: URLSessionDataTaskProtocol) {
lock.lock()
defer { lock.unlock() }
self.task = task
}
public func cancel() {
lock.lock()
defer { lock.unlock() }
task?.cancel()
task = nil
}
}

View File

@ -1,32 +0,0 @@
//
// PrefixPetSuffix.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public struct PrefixPetSuffix: Codable, JSONEncodable, Hashable {
public var testProperty: String
public init(testProperty: String) {
self.testProperty = testProperty
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case testProperty
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(testProperty, forKey: .testProperty)
}
}

View File

@ -1,56 +0,0 @@
//
// OpenISO8601DateFormatter.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
// https://stackoverflow.com/a/50281094/976628
public 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
}()
static let withoutTime: 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"
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 public func date(from string: String) -> Date? {
if let result = super.date(from: string) {
return result
} else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) {
return result
}
return OpenISO8601DateFormatter.withoutTime.date(from: string)
}
}

View File

@ -1,36 +0,0 @@
// 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

@ -1,670 +0,0 @@
// URLSessionImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if !os(macOS)
import MobileCoreServices
#endif
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
// Protocol defined for a session data task. This allows mocking out the URLSessionProtocol below since
// you may not want to create or return a real URLSessionDataTask.
public protocol URLSessionDataTaskProtocol {
func resume()
var taskIdentifier: Int { get }
var progress: Progress { get }
func cancel()
}
// Protocol allowing implementations to alter what is returned or to test their implementations.
public protocol URLSessionProtocol {
// Task which performs the network fetch. Expected to be from URLSession.dataTask(with:completionHandler:) such that a network request
// is sent off when `.resume()` is called.
func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}
extension URLSession: URLSessionProtocol {
// Passthrough to URLSession.dataTask(with:completionHandler) since URLSessionDataTask conforms to URLSessionDataTaskProtocol and fetches the network data.
public func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void) -> any URLSessionDataTaskProtocol {
return dataTask(with: request, completionHandler: completionHandler)
}
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
class URLSessionRequestBuilderFactory: RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type {
return URLSessionRequestBuilder<T>.self
}
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type {
return URLSessionDecodableRequestBuilder<T>.self
}
}
public typealias PetstoreClientAPIChallengeHandler = ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))
// Store the URLSession's delegate to retain its reference
private let sessionDelegate = SessionDelegate()
// Store the URLSession to retain its reference
private let defaultURLSession = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil)
// Store current taskDidReceiveChallenge for every URLSessionTask
private var challengeHandlerStore = SynchronizedDictionary<Int, PetstoreClientAPIChallengeHandler>()
// Store current URLCredential for every URLSessionTask
private var credentialStore = SynchronizedDictionary<Int, URLCredential>()
open class URLSessionRequestBuilder<T>: RequestBuilder<T> {
/**
May be assigned if you want to control the authentication challenges.
*/
public var taskDidReceiveChallenge: PetstoreClientAPIChallengeHandler?
required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication)
}
/**
May be overridden by a subclass if you want to control the URLSession
configuration.
*/
open func createURLSession() -> URLSessionProtocol {
return defaultURLSession
}
/**
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 URLRequest
configuration (e.g. to override the cache policy).
*/
open func createURLRequest(urlSession: URLSessionProtocol, 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)
}
let modifiedRequest = try encoding.encode(originalRequest, with: parameters)
return modifiedRequest
}
@discardableResult
override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) -> RequestTask {
let urlSession = createURLSession()
guard let xMethod = HTTPMethod(rawValue: method) else {
fatalError("Unsupported Http method - \(method)")
}
let encoding: ParameterEncoding
switch xMethod {
case .get, .head:
encoding = URLEncoding()
case .options, .post, .put, .patch, .delete, .trace, .connect:
let contentType = headers["Content-Type"] ?? "application/json"
if contentType.hasPrefix("application/") && contentType.contains("json") {
encoding = JSONDataEncoding()
} else if contentType.hasPrefix("multipart/form-data") {
encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:))
} else if contentType.hasPrefix("application/x-www-form-urlencoded") {
encoding = FormURLEncoding()
} else if contentType.hasPrefix("application/octet-stream"){
encoding = OctetStreamEncoding()
} else {
fatalError("Unsupported Media Type - \(contentType)")
}
}
do {
let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers)
var taskIdentifier: Int?
let cleanupRequest = {
if let taskIdentifier = taskIdentifier {
challengeHandlerStore[taskIdentifier] = nil
credentialStore[taskIdentifier] = nil
}
}
let dataTask = urlSession.dataTaskFromProtocol(with: request) { data, response, error in
apiResponseQueue.async {
self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion)
cleanupRequest()
}
}
onProgressReady?(dataTask.progress)
taskIdentifier = dataTask.taskIdentifier
challengeHandlerStore[dataTask.taskIdentifier] = taskDidReceiveChallenge
credentialStore[dataTask.taskIdentifier] = credential
dataTask.resume()
requestTask.set(task: dataTask)
} catch {
apiResponseQueue.async {
completion(.failure(ErrorResponse.error(415, nil, nil, error)))
}
}
return requestTask
}
fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) {
if let error = error {
completion(.failure(ErrorResponse.error(-1, data, response, error)))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
guard httpResponse.isStatusCodeSuccessful else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
return
}
switch T.self {
case is Void.Type:
completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
default:
fatalError("Unsupported Response Body Type - \(String(describing: T.self))")
}
}
open func buildHeaders() -> [String: String] {
var httpHeaders: [String: String] = [:]
for (key, value) in PetstoreClientAPI.customHeaders {
httpHeaders[key] = value
}
for (key, value) in 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?
for contentItem in items {
let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else {
continue
}
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
}
}
open class URLSessionDecodableRequestBuilder<T: Decodable>: URLSessionRequestBuilder<T> {
override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) {
if let error = error {
completion(.failure(ErrorResponse.error(-1, data, response, error)))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
guard httpResponse.isStatusCodeSuccessful else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
return
}
switch T.self {
case is String.Type:
let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
completion(.success(Response<T>(response: httpResponse, body: body as! T, bodyData: data)))
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 cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let requestURL = try getURL(from: urlRequest)
var requestPath = try getPath(from: requestURL)
if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) {
requestPath = requestPath.appending("/\(headerFileName)")
} else {
requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)")
}
let filePath = cachesDirectory.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, bodyData: data)))
} catch let requestParserError as DownloadException {
completion(.failure(ErrorResponse.error(400, data, response, requestParserError)))
} catch {
completion(.failure(ErrorResponse.error(400, data, response, error)))
}
case is Void.Type:
completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
case is Data.Type:
completion(.success(Response(response: httpResponse, body: data as! T, bodyData: data)))
default:
guard let unwrappedData = data, !unwrappedData.isEmpty else {
if let expressibleByNilLiteralType = T.self as? ExpressibleByNilLiteral.Type {
completion(.success(Response(response: httpResponse, body: expressibleByNilLiteralType.init(nilLiteral: ()) as! T, bodyData: data)))
} else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse)))
}
return
}
let decodeResult = CodableHelper.decode(T.self, from: unwrappedData)
switch decodeResult {
case let .success(decodableObj):
completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: unwrappedData)))
case let .failure(error):
completion(.failure(ErrorResponse.error(httpResponse.statusCode, unwrappedData, response, error)))
}
}
}
}
private class SessionDelegate: NSObject, URLSessionTaskDelegate {
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 = challengeHandlerStore[task.taskIdentifier] {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = credentialStore[task.taskIdentifier] ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
}
public 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"
}
public protocol ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest
}
private 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
}
}
private class FormDataEncoding: 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
guard let parameters = parameters, !parameters.isEmpty else {
return urlRequest
}
let boundary = "Boundary-\(UUID().uuidString)"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
for (key, value) in parameters {
for value in (value as? Array ?? [value]) {
switch value {
case let fileURL as URL:
urlRequest = try configureFileUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
fileURL: fileURL
)
case let string as String:
if let data = string.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
case let number as NSNumber:
if let data = number.stringValue.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
case let data as Data:
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
case let uuid as UUID:
if let data = uuid.uuidString.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
default:
fatalError("Unprocessable value \(value) with key \(key)")
}
}
}
var body = urlRequest.httpBody.orEmpty
body.append("\r\n--\(boundary)--\r\n")
urlRequest.httpBody = body
return urlRequest
}
private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest {
var urlRequest = urlRequest
var body = urlRequest.httpBody.orEmpty
let fileData = try Data(contentsOf: fileURL)
let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL)
let fileName = fileURL.lastPathComponent
// If we already added something then we need an additional newline.
if body.count > 0 {
body.append("\r\n")
}
// Value boundary.
body.append("--\(boundary)\r\n")
// Value headers.
body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n")
// Separate headers and body.
body.append("\r\n")
// The value data.
body.append(fileData)
urlRequest.httpBody = body
return urlRequest
}
private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest {
var urlRequest = urlRequest
var body = urlRequest.httpBody.orEmpty
// If we already added something then we need an additional newline.
if body.count > 0 {
body.append("\r\n")
}
// Value boundary.
body.append("--\(boundary)\r\n")
// Value headers.
body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n")
// Separate headers and body.
body.append("\r\n")
// The value data.
body.append(data)
urlRequest.httpBody = body
return urlRequest
}
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) {
#if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream"
}
#else
return "application/octet-stream"
#endif
} else {
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue(),
let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
return "application/octet-stream"
}
return "application/octet-stream"
}
}
private class FormURLEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
var urlRequest = urlRequest
var requestBodyComponents = URLComponents()
requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8)
return urlRequest
}
}
private class OctetStreamEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
var urlRequest = urlRequest
guard let body = parameters?["body"] else { return urlRequest }
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
}
switch body {
case let fileURL as URL:
urlRequest.httpBody = try Data(contentsOf: fileURL)
case let data as Data:
urlRequest.httpBody = data
default:
fatalError("Unprocessable body \(body)")
}
return urlRequest
}
}
private extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8.
///
/// - parameter string: The string to be added to the `Data`.
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
private extension Optional where Wrapped == Data {
var orEmpty: Data {
self ?? Data()
}
}
extension JSONDataEncoding: ParameterEncoding {}

View File

@ -1,161 +0,0 @@
// Validation.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct StringRule {
public var minLength: Int?
public var maxLength: Int?
public var pattern: String?
}
public struct NumericRule<T: Comparable & Numeric> {
public var minimum: T?
public var exclusiveMinimum = false
public var maximum: T?
public var exclusiveMaximum = false
public var multipleOf: T?
}
public struct ArrayRule {
public var minItems: Int?
public var maxItems: Int?
public var uniqueItems: Bool
}
public enum StringValidationErrorKind: Error {
case minLength, maxLength, pattern
}
public enum NumericValidationErrorKind: Error {
case minimum, maximum, multipleOf
}
public enum ArrayValidationErrorKind: Error {
case minItems, maxItems, uniqueItems
}
public struct ValidationError<T: Error & Hashable>: Error {
public fileprivate(set) var kinds: Set<T>
}
public struct Validator {
/// Validate a string against a rule.
/// - Parameter string: The String you wish to validate.
/// - Parameter rule: The StringRule you wish to use for validation.
/// - Returns: A validated string.
/// - Throws: `ValidationError<StringValidationErrorKind>` if the string is invalid against the rule,
/// `NSError` if the rule.pattern is invalid.
public static func validate(_ string: String, against rule: StringRule) throws -> String {
var error = ValidationError<StringValidationErrorKind>(kinds: [])
if let minLength = rule.minLength, !(minLength <= string.count) {
error.kinds.insert(.minLength)
}
if let maxLength = rule.maxLength, !(string.count <= maxLength) {
error.kinds.insert(.maxLength)
}
if let pattern = rule.pattern {
let matches = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
.matches(in: string, range: .init(location: 0, length: string.utf16.count))
if matches.isEmpty {
error.kinds.insert(.pattern)
}
}
guard error.kinds.isEmpty else {
throw error
}
return string
}
/// Validate a integer against a rule.
/// - Parameter numeric: The integer you wish to validate.
/// - Parameter rule: The NumericRule you wish to use for validation.
/// - Returns: A validated integer.
/// - Throws: `ValidationError<NumericValidationErrorKind>` if the numeric is invalid against the rule.
public static func validate<T: Comparable & BinaryInteger>(_ numeric: T, against rule: NumericRule<T>) throws -> T {
var error = ValidationError<NumericValidationErrorKind>(kinds: [])
if let minium = rule.minimum {
if !rule.exclusiveMinimum, minium > numeric {
error.kinds.insert(.minimum)
}
if rule.exclusiveMinimum, minium >= numeric {
error.kinds.insert(.minimum)
}
}
if let maximum = rule.maximum {
if !rule.exclusiveMaximum, numeric > maximum {
error.kinds.insert(.maximum)
}
if rule.exclusiveMaximum, numeric >= maximum {
error.kinds.insert(.maximum)
}
}
if let multipleOf = rule.multipleOf, !numeric.isMultiple(of: multipleOf) {
error.kinds.insert(.multipleOf)
}
guard error.kinds.isEmpty else {
throw error
}
return numeric
}
/// Validate a fractional number against a rule.
/// - Parameter numeric: The fractional number you wish to validate.
/// - Parameter rule: The NumericRule you wish to use for validation.
/// - Returns: A validated fractional number.
/// - Throws: `ValidationError<NumericValidationErrorKind>` if the numeric is invalid against the rule.
public static func validate<T: Comparable & FloatingPoint>(_ numeric: T, against rule: NumericRule<T>) throws -> T {
var error = ValidationError<NumericValidationErrorKind>(kinds: [])
if let minium = rule.minimum {
if !rule.exclusiveMinimum, minium > numeric {
error.kinds.insert(.minimum)
}
if rule.exclusiveMinimum, minium >= numeric {
error.kinds.insert(.minimum)
}
}
if let maximum = rule.maximum {
if !rule.exclusiveMaximum, numeric > maximum {
error.kinds.insert(.maximum)
}
if rule.exclusiveMaximum, numeric >= maximum {
error.kinds.insert(.maximum)
}
}
if let multipleOf = rule.multipleOf, numeric.remainder(dividingBy: multipleOf) != 0 {
error.kinds.insert(.multipleOf)
}
guard error.kinds.isEmpty else {
throw error
}
return numeric
}
/// Validate a array against a rule.
/// - Parameter array: The Array you wish to validate.
/// - Parameter rule: The ArrayRule you wish to use for validation.
/// - Returns: A validated array.
/// - Throws: `ValidationError<ArrayValidationErrorKind>` if the string is invalid against the rule.
public static func validate(_ array: Array<AnyHashable>, against rule: ArrayRule) throws -> Array<AnyHashable> {
var error = ValidationError<ArrayValidationErrorKind>(kinds: [])
if let minItems = rule.minItems, !(minItems <= array.count) {
error.kinds.insert(.minItems)
}
if let maxItems = rule.maxItems, !(array.count <= maxItems) {
error.kinds.insert(.maxItems)
}
if rule.uniqueItems {
let unique = Set(array)
if unique.count != array.count {
error.kinds.insert(.uniqueItems)
}
}
guard error.kinds.isEmpty else {
throw error
}
return array
}
}

View File

@ -1,47 +0,0 @@
# Swift5 API client for PetstoreClient
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client.
- API version: 1.0.0
- Package version:
- Generator version: 7.9.0-SNAPSHOT
- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen
## Installation
### Carthage
Run `carthage update`
### CocoaPods
Run `pod install`
## Documentation for API Endpoints
All URIs are relative to *http://localhost*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetsAPI* | [**petsGet**](docs/PetsAPI.md#petsget) | **GET** /pets |
*PetsAPI* | [**showPetById**](docs/PetsAPI.md#showpetbyid) | **GET** /pets/{petId} | Info for a specific pet
## Documentation For Models
- [PrefixPetSuffix](docs/PrefixPetSuffix.md)
<a id="documentation-for-authorization"></a>
## Documentation For Authorization
Endpoints do not require authorization.
## Author

View File

@ -1,101 +0,0 @@
# PetsAPI
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**petsGet**](PetsAPI.md#petsget) | **GET** /pets |
[**showPetById**](PetsAPI.md#showpetbyid) | **GET** /pets/{petId} | Info for a specific pet
# **petsGet**
```swift
open class func petsGet(completion: @escaping (_ data: PrefixPetSuffix?, _ error: Error?) -> Void)
```
### Example
```swift
// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new
import PetstoreClient
PetsAPI.petsGet() { (response, error) in
guard error == nil else {
print(error)
return
}
if (response) {
dump(response)
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**PrefixPetSuffix**](PrefixPetSuffix.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[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)
# **showPetById**
```swift
open class func showPetById(petId: String, completion: @escaping (_ data: AnyCodable?, _ error: Error?) -> Void)
```
Info for a specific pet
### Example
```swift
// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new
import PetstoreClient
let petId = "petId_example" // String | The id of the pet to retrieve
// Info for a specific pet
PetsAPI.showPetById(petId: petId) { (response, error) in
guard error == nil else {
print(error)
return
}
if (response) {
dump(response)
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **String** | The id of the pet to retrieve |
### Return type
**AnyCodable**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[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)

View File

@ -1,10 +0,0 @@
# PrefixPetSuffix
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**testProperty** | **String** | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

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

View File

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

View File

@ -1,15 +0,0 @@
name: PetstoreClient
targets:
PetstoreClient:
type: framework
platform: iOS
deploymentTarget: "11.0"
sources: [PetstoreClient]
info:
path: ./Info.plist
version: 1.0.0
settings:
APPLICATION_EXTENSION_API_ONLY: true
scheme: {}
dependencies:
- carthage: AnyCodable

View File

@ -1,3 +0,0 @@
#!/bin/sh
swift build && exit ${PIPESTATUS[0]}

View File

@ -111,7 +111,7 @@ open class Response<T> {
} }
public final class RequestTask: @unchecked Sendable { public final class RequestTask: @unchecked Sendable {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
private var task: URLSessionDataTaskProtocol? private var task: URLSessionDataTaskProtocol?
internal func set(task: URLSessionDataTaskProtocol) { internal func set(task: URLSessionDataTaskProtocol) {

View File

@ -9,28 +9,18 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.lock()
defer { lock.unlock() }
queue.sync { return self.dictionary[key]
value = self.dictionary[key]
}
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.lock()
defer { lock.unlock() }
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }
}
} }

View File

@ -585,7 +585,7 @@ private class FormDataEncoding: ParameterEncoding {
func mimeType(for url: URL) -> String { func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
#if canImport(UniformTypeIdentifiers) #if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) { if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream" return utType.preferredMIMEType ?? "application/octet-stream"

View File

@ -111,7 +111,7 @@ open class Response<T> {
} }
public final class RequestTask { public final class RequestTask {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
private var task: URLSessionDataTaskProtocol? private var task: URLSessionDataTaskProtocol?
internal func set(task: URLSessionDataTaskProtocol) { internal func set(task: URLSessionDataTaskProtocol) {

View File

@ -9,28 +9,18 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.lock()
defer { lock.unlock() }
queue.sync { return self.dictionary[key]
value = self.dictionary[key]
}
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.lock()
defer { lock.unlock() }
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }
}
} }

View File

@ -585,7 +585,7 @@ private class FormDataEncoding: ParameterEncoding {
func mimeType(for url: URL) -> String { func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
#if canImport(UniformTypeIdentifiers) #if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) { if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream" return utType.preferredMIMEType ?? "application/octet-stream"

View File

@ -111,7 +111,7 @@ open class Response<T> {
} }
public final class RequestTask { public final class RequestTask {
private var lock = NSRecursiveLock() private let lock = NSRecursiveLock()
private var task: URLSessionDataTaskProtocol? private var task: URLSessionDataTaskProtocol?
internal func set(task: URLSessionDataTaskProtocol) { internal func set(task: URLSessionDataTaskProtocol) {

View File

@ -9,28 +9,18 @@ import Foundation
internal struct SynchronizedDictionary<K: Hashable, V> { internal struct SynchronizedDictionary<K: Hashable, V> {
private var dictionary = [K: V]() private var dictionary = [K: V]()
private let queue = DispatchQueue( private let lock = NSRecursiveLock()
label: "SynchronizedDictionary",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
target: nil
)
internal subscript(key: K) -> V? { internal subscript(key: K) -> V? {
get { get {
var value: V? lock.lock()
defer { lock.unlock() }
queue.sync { return self.dictionary[key]
value = self.dictionary[key]
}
return value
} }
set { set {
queue.sync(flags: DispatchWorkItemFlags.barrier) { lock.lock()
defer { lock.unlock() }
self.dictionary[key] = newValue self.dictionary[key] = newValue
} }
} }
}
} }

View File

@ -585,7 +585,7 @@ private class FormDataEncoding: ParameterEncoding {
func mimeType(for url: URL) -> String { func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
#if canImport(UniformTypeIdentifiers) #if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) { if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream" return utType.preferredMIMEType ?? "application/octet-stream"

View File

@ -1,100 +0,0 @@
# Created by https://www.toptal.com/developers/gitignore/api/xcode,swift
# Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift
### Swift ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
## Obj-C/Swift specific
*.hmap
## App packaging
*.ipa
*.dSYM.zip
*.dSYM
## 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/
# Package.pins
# Package.resolved
# *.xcodeproj
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm
.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/
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build/
# Accio dependency management
Dependencies/
.accio/
# 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://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output
# Code Injection
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
### Xcode ###
## Xcode 8 and earlier
### Xcode Patch ###
*.xcodeproj/*
!*.xcodeproj/project.pbxproj
!*.xcodeproj/xcshareddata/
!*.xcworkspace/contents.xcworkspacedata
/*.gcno
**/xcshareddata/WorkspaceSettings.xcsettings
# End of https://www.toptal.com/developers/gitignore/api/xcode,swift

View File

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

View File

@ -1,38 +0,0 @@
.gitignore
.swiftformat
Cartfile
Package.swift
PetstoreClient.podspec
PetstoreClient/Classes/OpenAPIs/APIHelper.swift
PetstoreClient/Classes/OpenAPIs/APIs.swift
PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift
PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift
PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift
PetstoreClient/Classes/OpenAPIs/CodableHelper.swift
PetstoreClient/Classes/OpenAPIs/Configuration.swift
PetstoreClient/Classes/OpenAPIs/Extensions.swift
PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift
PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift
PetstoreClient/Classes/OpenAPIs/Models.swift
PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift
PetstoreClient/Classes/OpenAPIs/Models/Category.swift
PetstoreClient/Classes/OpenAPIs/Models/Order.swift
PetstoreClient/Classes/OpenAPIs/Models/Pet.swift
PetstoreClient/Classes/OpenAPIs/Models/Tag.swift
PetstoreClient/Classes/OpenAPIs/Models/User.swift
PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift
PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift
PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift
PetstoreClient/Classes/OpenAPIs/Validation.swift
README.md
docs/ApiResponse.md
docs/Category.md
docs/Order.md
docs/Pet.md
docs/PetAPI.md
docs/StoreAPI.md
docs/Tag.md
docs/User.md
docs/UserAPI.md
git_push.sh
project.yml

View File

@ -1,45 +0,0 @@
# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/
#
# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md
#
# file options
# uncomment below to exclude files, folders
#--exclude path/to/test1.swift,Snapshots,Build
# format options
--allman false
--binarygrouping 4,8
--commas always
--comments indent
--decimalgrouping 3,6
--elseposition same-line
--empty void
--exponentcase lowercase
--exponentgrouping disabled
--fractiongrouping disabled
--header ignore
--hexgrouping 4,8
--hexliteralcase uppercase
--ifdef indent
--indent 4
--indentcase false
--importgrouping testable-bottom
--linebreaks lf
--maxwidth none
--octalgrouping 4,8
--operatorfunc spaced
--patternlet hoist
--ranges spaced
--self remove
--semicolons inline
--stripunusedargs always
--swiftversion 5.4
--trimwhitespace always
--wraparguments preserve
--wrapcollections preserve
# rules
--enable isEmpty

View File

@ -1 +0,0 @@
github "Flight-School/AnyCodable" ~> 0.6

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -1,16 +0,0 @@
{
"object": {
"pins": [
{
"package": "AnyCodable",
"repositoryURL": "https://github.com/Flight-School/AnyCodable",
"state": {
"branch": null,
"revision": "56901f2af3625b38924d488b612e95fe8846ee9b",
"version": "0.6.6"
}
}
]
},
"version": 1
}

View File

@ -1,33 +0,0 @@
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "PetstoreClient",
platforms: [
.iOS(.v11),
.macOS(.v10_13),
.tvOS(.v11),
.watchOS(.v4),
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "PetstoreClient",
targets: ["PetstoreClient"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/Flight-School/AnyCodable", .upToNextMajor(from: "0.6.1")),
],
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: "PetstoreClient",
dependencies: ["AnyCodable", ],
path: "PetstoreClient/Classes"
),
]
)

View File

@ -1,15 +0,0 @@
Pod::Spec.new do |s|
s.name = 'PetstoreClient'
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.tvos.deployment_target = '11.0'
s.watchos.deployment_target = '4.0'
s.version = '1.0.0'
s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' }
s.authors = ''
s.license = 'Proprietary'
s.homepage = 'https://github.com/openapitools/openapi-generator'
s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/**/*.swift'
s.dependency 'AnyCodable-FlightSchool', '~> 0.6'
end

View File

@ -1,121 +0,0 @@
// APIHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
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? [Any?] {
result[item.key] = collection
.compactMap { value in convertAnyToString(value) }
.joined(separator: ",")
} else if let value: Any = item.value {
result[item.key] = convertAnyToString(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 convertAnyToString(_ value: Any?) -> String? {
guard let value = value else { return nil }
if let value = value as? any RawRepresentable {
return "\(value.rawValue)"
} else {
return "\(value)"
}
}
public static func mapValueToPathItem(_ source: Any) -> Any {
if let collection = source as? [Any?] {
return collection
.compactMap { value in convertAnyToString(value) }
.joined(separator: ",")
} else if let value = source as? any RawRepresentable {
return "\(value.rawValue)"
}
return source
}
/// maps all values from source to query parameters
///
/// explode attribute is respected: collection values might be either joined or split up into separate key value pairs
public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? {
let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in
if let collection = item.value.wrappedValue as? [Any?] {
let collectionValues: [String] = collection.compactMap { value in convertAnyToString(value) }
if !item.value.isExplode {
result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ",")))
} else {
collectionValues
.forEach { value in
result.append(URLQueryItem(name: item.key, value: value))
}
}
} else if let value = item.value.wrappedValue {
result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
}
}
if destination.isEmpty {
return nil
}
return destination.sorted { $0.name < $1.name }
}
/// maps all values from source to query parameters
///
/// collection values are always exploded
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? [Any?] {
collection
.compactMap { value in convertAnyToString(value) }
.forEach { value in
result.append(URLQueryItem(name: item.key, value: value))
}
} else if let value = item.value {
result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
}
}
if destination.isEmpty {
return nil
}
return destination.sorted { $0.name < $1.name }
}
}

View File

@ -1,68 +0,0 @@
// APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
open class PetstoreClientAPI {
public static var basePath = "http://petstore.swagger.io/v2"
public static var customHeaders: [String: String] = [:]
public static var credential: URLCredential?
public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory()
public static var apiResponseQueue: DispatchQueue = .main
}
open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String: String]
public let parameters: [String: Any]?
public let method: String
public let URLString: String
public let requestTask: RequestTask = RequestTask()
public let requiresAuthentication: Bool
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((Progress) -> Void)?
required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.headers = headers
self.requiresAuthentication = requiresAuthentication
addHeaders(PetstoreClientAPI.customHeaders)
}
open func addHeaders(_ aHeaders: [String: String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
@discardableResult
open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) -> RequestTask {
return requestTask
}
public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
open func addCredential() -> Self {
credential = PetstoreClientAPI.credential
return self
}
}
public protocol RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type
}

View File

@ -1,441 +0,0 @@
//
// PetAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class PetAPI {
/**
Add a new pet to the store
- parameter pet: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func addPet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return addPetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Add a new pet to the store
- POST /pet
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter pet: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func addPetWithRequestBuilder(pet: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Deletes a pet
- DELETE /pet/{petId}
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- returns: RequestBuilder<Void>
*/
open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"api_key": apiKey?.encodeToJSON(),
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
* enum for parameter status
*/
public enum Status_findPetsByStatus: String, CaseIterable {
case available = "available"
case pending = "pending"
case sold = "sold"
}
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> RequestTask {
return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Finds Pets by status
- GET /pet/findByStatus
- Multiple status values can be provided with comma separated strings
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter status: (query) Status values that need to be considered for filter
- returns: RequestBuilder<[Pet]>
*/
open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByStatus"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"status": (wrappedValue: status.encodeToJSON(), isExplode: false),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@available(*, deprecated, message: "This operation is deprecated.")
@discardableResult
open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> RequestTask {
return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Finds Pets by tags
- GET /pet/findByTags
- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter tags: (query) Tags to filter by
- returns: RequestBuilder<[Pet]>
*/
@available(*, deprecated, message: "This operation is deprecated.")
open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByTags"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"tags": (wrappedValue: tags.encodeToJSON(), isExplode: false),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Find pet by ID
- parameter petId: (path) ID of pet to return
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) -> RequestTask {
return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Find pet by ID
- GET /pet/{petId}
- Returns a single pet
- API Key:
- type: apiKey api_key (HEADER)
- name: api_key
- parameter petId: (path) ID of pet to return
- returns: RequestBuilder<Pet>
*/
open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder<Pet> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Update an existing pet
- parameter pet: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func updatePet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return updatePetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Update an existing pet
- PUT /pet
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter pet: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func updatePetWithRequestBuilder(pet: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Updates a pet in the store with form data
- POST /pet/{petId}
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: RequestBuilder<Void>
*/
open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"name": name?.encodeToJSON(),
"status": status?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/x-www-form-urlencoded",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) -> RequestTask {
return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder<ApiResponse> {
var localVariablePath = "/pet/{petId}/uploadImage"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"additionalMetadata": additionalMetadata?.encodeToJSON(),
"file": file?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "multipart/form-data",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
}

View File

@ -1,197 +0,0 @@
//
// StoreAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class StoreAPI {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Delete purchase order by ID
- DELETE /store/order/{orderId}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder<Void> {
var localVariablePath = "/store/order/{orderId}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Returns pet inventories by status
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) -> RequestTask {
return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Returns pet inventories by status
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key (HEADER)
- name: api_key
- returns: RequestBuilder<[String: Int]>
*/
open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> {
let localVariablePath = "/store/inventory"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> RequestTask {
return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Find purchase order by ID
- GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder<Order> {
var localVariablePath = "/store/order/{orderId}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Place an order for a pet
- parameter order: (body) order placed for purchasing the pet
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> RequestTask {
return placeOrderWithRequestBuilder(order: order).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Place an order for a pet
- POST /store/order
-
- parameter order: (body) order placed for purchasing the pet
- returns: RequestBuilder<Order>
*/
open class func placeOrderWithRequestBuilder(order: Order) -> RequestBuilder<Order> {
let localVariablePath = "/store/order"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: order)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
}

View File

@ -1,400 +0,0 @@
//
// UserAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class UserAPI {
/**
Create user
- parameter user: (body) Created user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func createUser(user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return createUserWithRequestBuilder(user: user).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Create user
- POST /user
- This can only be done by the logged in user.
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- parameter user: (body) Created user object
- returns: RequestBuilder<Void>
*/
open class func createUserWithRequestBuilder(user: User) -> RequestBuilder<Void> {
let localVariablePath = "/user"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Creates list of users with given input array
- parameter user: (body) List of user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func createUsersWithArrayInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return createUsersWithArrayInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Creates list of users with given input array
- POST /user/createWithArray
-
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- parameter user: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithArrayInputWithRequestBuilder(user: [User]) -> RequestBuilder<Void> {
let localVariablePath = "/user/createWithArray"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Creates list of users with given input array
- parameter user: (body) List of user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func createUsersWithListInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return createUsersWithListInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Creates list of users with given input array
- POST /user/createWithList
-
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- parameter user: (body) List of user object
- returns: RequestBuilder<Void>
*/
open class func createUsersWithListInputWithRequestBuilder(user: [User]) -> RequestBuilder<Void> {
let localVariablePath = "/user/createWithList"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Delete user
- DELETE /user/{username}
- This can only be done by the logged in user.
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- parameter username: (path) The name that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> {
var localVariablePath = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) -> RequestTask {
return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Get user by user name
- GET /user/{username}
-
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
*/
open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> {
var localVariablePath = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Logs user into the system
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> RequestTask {
return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Logs user into the system
- GET /user/login
-
- responseHeaders: [Set-Cookie(String), X-Rate-Limit(Int), X-Expires-After(Date)]
- parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text
- returns: RequestBuilder<String>
*/
open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> {
let localVariablePath = "/user/login"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"username": (wrappedValue: username.encodeToJSON(), isExplode: true),
"password": (wrappedValue: password.encodeToJSON(), isExplode: true),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Logs out current logged in user session
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Logs out current logged in user session
- GET /user/logout
-
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- returns: RequestBuilder<Void>
*/
open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let localVariablePath = "/user/logout"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter user: (body) Updated user object
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func updateUser(username: String, user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return updateUserWithRequestBuilder(username: username, user: user).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Updated user
- PUT /user/{username}
- This can only be done by the logged in user.
- API Key:
- type: apiKey AUTH_KEY
- name: auth_cookie
- parameter username: (path) name that need to be deleted
- parameter user: (body) Updated user object
- returns: RequestBuilder<Void>
*/
open class func updateUserWithRequestBuilder(username: String, user: User) -> RequestBuilder<Void> {
var localVariablePath = "/user/{username}"
let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/json",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
}

View File

@ -1,49 +0,0 @@
//
// CodableHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open 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
}()
public static var dateFormatter: DateFormatter {
get { return customDateFormatter ?? defaultDateFormatter }
set { customDateFormatter = newValue }
}
public static var jsonDecoder: JSONDecoder {
get { return customJSONDecoder ?? defaultJSONDecoder }
set { customJSONDecoder = newValue }
}
public static var jsonEncoder: JSONEncoder {
get { return customJSONEncoder ?? defaultJSONEncoder }
set { customJSONEncoder = newValue }
}
open class func decode<T>(_ type: T.Type, from data: Data) -> Swift.Result<T, Error> where T: Decodable {
return Swift.Result { try jsonDecoder.decode(type, from: data) }
}
open class func encode<T>(_ value: T) -> Swift.Result<Data, Error> where T: Encodable {
return Swift.Result { try jsonEncoder.encode(value) }
}
}

View File

@ -1,18 +0,0 @@
// Configuration.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
open class Configuration {
/// Configures the range of HTTP status codes that will result in a successful response
///
/// If a HTTP status code is outside of this range the response will be interpreted as failed.
public static var successfulStatusCodeRange: Range = 200..<300
}

View File

@ -1,236 +0,0 @@
// Extensions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
#if canImport(AnyCodable)
import AnyCodable
#endif
extension Bool: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Float: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int32: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Int64: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Double: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension Decimal: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension String: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension URL: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension UUID: JSONEncodable {
func encodeToJSON() -> Any { self }
}
extension RawRepresentable where RawValue: JSONEncodable {
func encodeToJSON() -> Any { return self.rawValue }
}
private func encodeIfPossible<T>(_ object: T) -> Any {
if let encodableObject = object as? JSONEncodable {
return encodableObject.encodeToJSON()
} else {
return object
}
}
extension Array: JSONEncodable {
func encodeToJSON() -> Any {
return self.map(encodeIfPossible)
}
}
extension Set: JSONEncodable {
func encodeToJSON() -> Any {
return Array(self).encodeToJSON()
}
}
extension Dictionary: JSONEncodable {
func encodeToJSON() -> Any {
var dictionary = [AnyHashable: Any]()
for (key, value) in self {
dictionary[key] = encodeIfPossible(value)
}
return dictionary
}
}
extension Data: JSONEncodable {
func encodeToJSON() -> Any {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
extension Date: JSONEncodable {
func encodeToJSON() -> Any {
return CodableHelper.dateFormatter.string(from: self)
}
}
extension JSONEncodable where Self: Encodable {
func encodeToJSON() -> Any {
guard let data = try? CodableHelper.jsonEncoder.encode(self) else {
fatalError("Could not encode to json: \(self)")
}
return data.encodeToJSON()
}
}
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)
}
}
public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws {
let decimalNumber = NSDecimalNumber(decimal: value)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale(identifier: "en_US")
let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)"
try encode(formattedString, forKey: key)
}
public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws {
if let value = value {
try encode(value, forKey: key)
}
}
}
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]?
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
}
public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal {
let stringValue = try decode(String.self, forKey: key)
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? {
guard let stringValue = try decodeIfPresent(String.self, forKey: key) else {
return nil
}
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
}
extension HTTPURLResponse {
var isStatusCodeSuccessful: Bool {
return Configuration.successfulStatusCodeRange.contains(statusCode)
}
}

View File

@ -1,56 +0,0 @@
//
// JSONDataEncoding.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public 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.
public 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
}
public static func encodingParameters(jsonData: Data?) -> [String: Any]? {
var returnedParams: [String: Any]?
if let jsonData = jsonData, !jsonData.isEmpty {
var params: [String: Any] = [:]
params[jsonDataKey] = jsonData
returnedParams = params
}
return returnedParams
}
}

View File

@ -1,45 +0,0 @@
//
// JSONEncodingHelper.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class JSONEncodingHelper {
open class func encodingParameters<T: Encodable>(forEncodableObject encodableObj: T?) -> [String: Any]? {
var params: [String: Any]?
// 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
}
open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? {
var params: [String: Any]?
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

@ -1,129 +0,0 @@
// Models.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
protocol JSONEncodable {
func encodeToJSON() -> Any
}
/// An enum where the last case value can be used as a default catch-all.
protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable
where RawValue: Decodable, AllCases: BidirectionalCollection {}
extension CaseIterableDefaultsLast {
/// Initializes an enum such that if a known raw value is found, then it is decoded.
/// Otherwise the last case is used.
/// - Parameter decoder: A decoder.
public init(from decoder: Decoder) throws {
if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) {
self = value
} else if let lastValue = Self.allCases.last {
self = lastValue
} else {
throw DecodingError.valueNotFound(
Self.Type.self,
.init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast")
)
}
}
}
/// A flexible type that can be encoded (`.encodeNull` or `.encodeValue`)
/// or not encoded (`.encodeNothing`). Intended for request payloads.
public enum NullEncodable<Wrapped: Hashable>: Hashable {
case encodeNothing
case encodeNull
case encodeValue(Wrapped)
}
extension NullEncodable: Codable where Wrapped: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Wrapped.self) {
self = .encodeValue(value)
} else if container.decodeNil() {
self = .encodeNull
} else {
self = .encodeNothing
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .encodeNothing: return
case .encodeNull: try container.encodeNil()
case .encodeValue(let wrapped): try container.encode(wrapped)
}
}
}
public enum ErrorResponse: Error {
case error(Int, Data?, URLResponse?, Error)
}
public enum DownloadException: Error {
case responseDataMissing
case responseFailed
case requestMissing
case requestMissingPath
case requestMissingURL
}
public enum DecodableRequestBuilderError: Error {
case emptyDataResponse
case nilHTTPResponse
case unsuccessfulHTTPStatusCode
case jsonDecoding(DecodingError)
case generalError(Error)
}
open class Response<T> {
public let statusCode: Int
public let header: [String: String]
public let body: T
public let bodyData: Data?
public init(statusCode: Int, header: [String: String], body: T, bodyData: Data?) {
self.statusCode = statusCode
self.header = header
self.body = body
self.bodyData = bodyData
}
public convenience init(response: HTTPURLResponse, body: T, bodyData: Data?) {
let rawHeader = response.allHeaderFields
var responseHeader = [String: String]()
for (key, value) in rawHeader {
if let key = key.base as? String, let value = value as? String {
responseHeader[key] = value
}
}
self.init(statusCode: response.statusCode, header: responseHeader, body: body, bodyData: bodyData)
}
}
public final class RequestTask {
private var lock = NSRecursiveLock()
private var task: URLSessionDataTaskProtocol?
internal func set(task: URLSessionDataTaskProtocol) {
lock.lock()
defer { lock.unlock() }
self.task = task
}
public func cancel() {
lock.lock()
defer { lock.unlock() }
task?.cancel()
task = nil
}
}

View File

@ -1,41 +0,0 @@
//
// ApiResponse.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** Describes the result of uploading an image resource */
public struct ApiResponse: Codable, JSONEncodable, Hashable {
public var code: Int?
public var type: String?
public var message: String?
public init(code: Int? = nil, type: String? = nil, message: String? = nil) {
self.code = code
self.type = type
self.message = message
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case code
case type
case message
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(code, forKey: .code)
try container.encodeIfPresent(type, forKey: .type)
try container.encodeIfPresent(message, forKey: .message)
}
}

View File

@ -1,38 +0,0 @@
//
// Category.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A category for a pet */
public struct Category: Codable, JSONEncodable, Hashable {
static let nameRule = StringRule(minLength: nil, maxLength: nil, pattern: "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/")
public var id: Int64?
public var name: String?
public init(id: Int64? = nil, name: String? = nil) {
self.id = id
self.name = name
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case name
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(name, forKey: .name)
}
}

View File

@ -1,22 +0,0 @@
//
// InlineObject.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct InlineObject: Codable {
/** Updated name of the pet */
public var name: String?
/** Updated status of the pet */
public var status: String?
public init(name: String? = nil, status: String? = nil) {
self.name = name
self.status = status
}
}

View File

@ -1,22 +0,0 @@
//
// InlineObject1.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct InlineObject1: Codable {
/** Additional data to pass to server */
public var additionalMetadata: String?
/** file to upload */
public var file: URL?
public init(additionalMetadata: String? = nil, file: URL? = nil) {
self.additionalMetadata = additionalMetadata
self.file = file
}
}

View File

@ -1,60 +0,0 @@
//
// Order.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** An order for a pets from the pet store */
@available(*, deprecated, message: "This schema is deprecated.")
public struct Order: Codable, JSONEncodable, Hashable {
public enum Status: String, Codable, CaseIterable {
case placed = "placed"
case approved = "approved"
case delivered = "delivered"
}
public var id: Int64?
public var petId: Int64?
public var quantity: Int?
public var shipDate: Date?
/** Order Status */
public var status: Status?
public var complete: Bool? = false
public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) {
self.id = id
self.petId = petId
self.quantity = quantity
self.shipDate = shipDate
self.status = status
self.complete = complete
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case petId
case quantity
case shipDate
case status
case complete
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(petId, forKey: .petId)
try container.encodeIfPresent(quantity, forKey: .quantity)
try container.encodeIfPresent(shipDate, forKey: .shipDate)
try container.encodeIfPresent(status, forKey: .status)
try container.encodeIfPresent(complete, forKey: .complete)
}
}

View File

@ -1,60 +0,0 @@
//
// Pet.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A pet for sale in the pet store */
public struct Pet: Codable, JSONEncodable, Hashable {
public enum Status: String, Codable, CaseIterable {
case available = "available"
case pending = "pending"
case sold = "sold"
}
public var id: Int64?
public var category: Category?
public var name: String?
@available(*, deprecated, message: "This property is deprecated.")
public var photoUrls: [String]
public var tags: [Tag]?
/** pet status in the store */
public var status: Status?
public init(id: Int64? = nil, category: Category? = nil, name: String?, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) {
self.id = id
self.category = category
self.name = name
self.photoUrls = photoUrls
self.tags = tags
self.status = status
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case category
case name
case photoUrls
case tags
case status
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(category, forKey: .category)
try container.encode(name, forKey: .name)
try container.encode(photoUrls, forKey: .photoUrls)
try container.encodeIfPresent(tags, forKey: .tags)
try container.encodeIfPresent(status, forKey: .status)
}
}

View File

@ -1,37 +0,0 @@
//
// Tag.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A tag for a pet */
public struct Tag: Codable, JSONEncodable, Hashable {
public var id: Int64?
public var name: String?
public init(id: Int64? = nil, name: String? = nil) {
self.id = id
self.name = name
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case name
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(name, forKey: .name)
}
}

View File

@ -1,62 +0,0 @@
//
// User.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A User who is purchasing from the pet store */
public struct User: Codable, JSONEncodable, Hashable {
public var id: Int64?
public var username: String?
public var firstName: String?
public var lastName: String?
public var email: String?
public var password: String?
public var phone: String?
/** User Status */
public var userStatus: Int?
public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) {
self.id = id
self.username = username
self.firstName = firstName
self.lastName = lastName
self.email = email
self.password = password
self.phone = phone
self.userStatus = userStatus
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case username
case firstName
case lastName
case email
case password
case phone
case userStatus
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(username, forKey: .username)
try container.encodeIfPresent(firstName, forKey: .firstName)
try container.encodeIfPresent(lastName, forKey: .lastName)
try container.encodeIfPresent(email, forKey: .email)
try container.encodeIfPresent(password, forKey: .password)
try container.encodeIfPresent(phone, forKey: .phone)
try container.encodeIfPresent(userStatus, forKey: .userStatus)
}
}

View File

@ -1,56 +0,0 @@
//
// OpenISO8601DateFormatter.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
// https://stackoverflow.com/a/50281094/976628
public 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
}()
static let withoutTime: 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"
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 public func date(from string: String) -> Date? {
if let result = super.date(from: string) {
return result
} else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) {
return result
}
return OpenISO8601DateFormatter.withoutTime.date(from: string)
}
}

View File

@ -1,36 +0,0 @@
// 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

@ -1,670 +0,0 @@
// URLSessionImplementations.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if !os(macOS)
import MobileCoreServices
#endif
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
// Protocol defined for a session data task. This allows mocking out the URLSessionProtocol below since
// you may not want to create or return a real URLSessionDataTask.
public protocol URLSessionDataTaskProtocol {
func resume()
var taskIdentifier: Int { get }
var progress: Progress { get }
func cancel()
}
// Protocol allowing implementations to alter what is returned or to test their implementations.
public protocol URLSessionProtocol {
// Task which performs the network fetch. Expected to be from URLSession.dataTask(with:completionHandler:) such that a network request
// is sent off when `.resume()` is called.
func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}
extension URLSession: URLSessionProtocol {
// Passthrough to URLSession.dataTask(with:completionHandler) since URLSessionDataTask conforms to URLSessionDataTaskProtocol and fetches the network data.
public func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void) -> any URLSessionDataTaskProtocol {
return dataTask(with: request, completionHandler: completionHandler)
}
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
class URLSessionRequestBuilderFactory: RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type {
return URLSessionRequestBuilder<T>.self
}
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type {
return URLSessionDecodableRequestBuilder<T>.self
}
}
public typealias PetstoreClientAPIChallengeHandler = ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))
// Store the URLSession's delegate to retain its reference
private let sessionDelegate = SessionDelegate()
// Store the URLSession to retain its reference
private let defaultURLSession = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil)
// Store current taskDidReceiveChallenge for every URLSessionTask
private var challengeHandlerStore = SynchronizedDictionary<Int, PetstoreClientAPIChallengeHandler>()
// Store current URLCredential for every URLSessionTask
private var credentialStore = SynchronizedDictionary<Int, URLCredential>()
open class URLSessionRequestBuilder<T>: RequestBuilder<T> {
/**
May be assigned if you want to control the authentication challenges.
*/
public var taskDidReceiveChallenge: PetstoreClientAPIChallengeHandler?
required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication)
}
/**
May be overridden by a subclass if you want to control the URLSession
configuration.
*/
open func createURLSession() -> URLSessionProtocol {
return defaultURLSession
}
/**
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 URLRequest
configuration (e.g. to override the cache policy).
*/
open func createURLRequest(urlSession: URLSessionProtocol, 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)
}
let modifiedRequest = try encoding.encode(originalRequest, with: parameters)
return modifiedRequest
}
@discardableResult
override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) -> RequestTask {
let urlSession = createURLSession()
guard let xMethod = HTTPMethod(rawValue: method) else {
fatalError("Unsupported Http method - \(method)")
}
let encoding: ParameterEncoding
switch xMethod {
case .get, .head:
encoding = URLEncoding()
case .options, .post, .put, .patch, .delete, .trace, .connect:
let contentType = headers["Content-Type"] ?? "application/json"
if contentType.hasPrefix("application/") && contentType.contains("json") {
encoding = JSONDataEncoding()
} else if contentType.hasPrefix("multipart/form-data") {
encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:))
} else if contentType.hasPrefix("application/x-www-form-urlencoded") {
encoding = FormURLEncoding()
} else if contentType.hasPrefix("application/octet-stream"){
encoding = OctetStreamEncoding()
} else {
fatalError("Unsupported Media Type - \(contentType)")
}
}
do {
let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers)
var taskIdentifier: Int?
let cleanupRequest = {
if let taskIdentifier = taskIdentifier {
challengeHandlerStore[taskIdentifier] = nil
credentialStore[taskIdentifier] = nil
}
}
let dataTask = urlSession.dataTaskFromProtocol(with: request) { data, response, error in
apiResponseQueue.async {
self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion)
cleanupRequest()
}
}
onProgressReady?(dataTask.progress)
taskIdentifier = dataTask.taskIdentifier
challengeHandlerStore[dataTask.taskIdentifier] = taskDidReceiveChallenge
credentialStore[dataTask.taskIdentifier] = credential
dataTask.resume()
requestTask.set(task: dataTask)
} catch {
apiResponseQueue.async {
completion(.failure(ErrorResponse.error(415, nil, nil, error)))
}
}
return requestTask
}
fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) {
if let error = error {
completion(.failure(ErrorResponse.error(-1, data, response, error)))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
guard httpResponse.isStatusCodeSuccessful else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
return
}
switch T.self {
case is Void.Type:
completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
default:
fatalError("Unsupported Response Body Type - \(String(describing: T.self))")
}
}
open func buildHeaders() -> [String: String] {
var httpHeaders: [String: String] = [:]
for (key, value) in PetstoreClientAPI.customHeaders {
httpHeaders[key] = value
}
for (key, value) in 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?
for contentItem in items {
let filenameKey = "filename="
guard let range = contentItem.range(of: filenameKey) else {
continue
}
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
}
}
open class URLSessionDecodableRequestBuilder<T: Decodable>: URLSessionRequestBuilder<T> {
override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result<Response<T>, ErrorResponse>) -> Void) {
if let error = error {
completion(.failure(ErrorResponse.error(-1, data, response, error)))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
return
}
guard httpResponse.isStatusCodeSuccessful else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
return
}
switch T.self {
case is String.Type:
let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
completion(.success(Response<T>(response: httpResponse, body: body as! T, bodyData: data)))
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 cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let requestURL = try getURL(from: urlRequest)
var requestPath = try getPath(from: requestURL)
if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) {
requestPath = requestPath.appending("/\(headerFileName)")
} else {
requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)")
}
let filePath = cachesDirectory.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, bodyData: data)))
} catch let requestParserError as DownloadException {
completion(.failure(ErrorResponse.error(400, data, response, requestParserError)))
} catch {
completion(.failure(ErrorResponse.error(400, data, response, error)))
}
case is Void.Type:
completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
case is Data.Type:
completion(.success(Response(response: httpResponse, body: data as! T, bodyData: data)))
default:
guard let unwrappedData = data, !unwrappedData.isEmpty else {
if let expressibleByNilLiteralType = T.self as? ExpressibleByNilLiteral.Type {
completion(.success(Response(response: httpResponse, body: expressibleByNilLiteralType.init(nilLiteral: ()) as! T, bodyData: data)))
} else {
completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse)))
}
return
}
let decodeResult = CodableHelper.decode(T.self, from: unwrappedData)
switch decodeResult {
case let .success(decodableObj):
completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: unwrappedData)))
case let .failure(error):
completion(.failure(ErrorResponse.error(httpResponse.statusCode, unwrappedData, response, error)))
}
}
}
}
private class SessionDelegate: NSObject, URLSessionTaskDelegate {
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 = challengeHandlerStore[task.taskIdentifier] {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = credentialStore[task.taskIdentifier] ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
}
public 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"
}
public protocol ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest
}
private 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
}
}
private class FormDataEncoding: 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
guard let parameters = parameters, !parameters.isEmpty else {
return urlRequest
}
let boundary = "Boundary-\(UUID().uuidString)"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
for (key, value) in parameters {
for value in (value as? Array ?? [value]) {
switch value {
case let fileURL as URL:
urlRequest = try configureFileUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
fileURL: fileURL
)
case let string as String:
if let data = string.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
case let number as NSNumber:
if let data = number.stringValue.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
case let data as Data:
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
case let uuid as UUID:
if let data = uuid.uuidString.data(using: .utf8) {
urlRequest = configureDataUploadRequest(
urlRequest: urlRequest,
boundary: boundary,
name: key,
data: data
)
}
default:
fatalError("Unprocessable value \(value) with key \(key)")
}
}
}
var body = urlRequest.httpBody.orEmpty
body.append("\r\n--\(boundary)--\r\n")
urlRequest.httpBody = body
return urlRequest
}
private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest {
var urlRequest = urlRequest
var body = urlRequest.httpBody.orEmpty
let fileData = try Data(contentsOf: fileURL)
let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL)
let fileName = fileURL.lastPathComponent
// If we already added something then we need an additional newline.
if body.count > 0 {
body.append("\r\n")
}
// Value boundary.
body.append("--\(boundary)\r\n")
// Value headers.
body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n")
// Separate headers and body.
body.append("\r\n")
// The value data.
body.append(fileData)
urlRequest.httpBody = body
return urlRequest
}
private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest {
var urlRequest = urlRequest
var body = urlRequest.httpBody.orEmpty
// If we already added something then we need an additional newline.
if body.count > 0 {
body.append("\r\n")
}
// Value boundary.
body.append("--\(boundary)\r\n")
// Value headers.
body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n")
// Separate headers and body.
body.append("\r\n")
// The value data.
body.append(data)
urlRequest.httpBody = body
return urlRequest
}
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if #available(iOS 15, macOS 11, *) {
#if canImport(UniformTypeIdentifiers)
if let utType = UTType(filenameExtension: pathExtension) {
return utType.preferredMIMEType ?? "application/octet-stream"
}
#else
return "application/octet-stream"
#endif
} else {
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue(),
let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
return "application/octet-stream"
}
return "application/octet-stream"
}
}
private class FormURLEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
var urlRequest = urlRequest
var requestBodyComponents = URLComponents()
requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8)
return urlRequest
}
}
private class OctetStreamEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
var urlRequest = urlRequest
guard let body = parameters?["body"] else { return urlRequest }
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
}
switch body {
case let fileURL as URL:
urlRequest.httpBody = try Data(contentsOf: fileURL)
case let data as Data:
urlRequest.httpBody = data
default:
fatalError("Unprocessable body \(body)")
}
return urlRequest
}
}
private extension Data {
/// Append string to Data
///
/// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8.
///
/// - parameter string: The string to be added to the `Data`.
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
private extension Optional where Wrapped == Data {
var orEmpty: Data {
self ?? Data()
}
}
extension JSONDataEncoding: ParameterEncoding {}

View File

@ -1,161 +0,0 @@
// Validation.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct StringRule {
public var minLength: Int?
public var maxLength: Int?
public var pattern: String?
}
public struct NumericRule<T: Comparable & Numeric> {
public var minimum: T?
public var exclusiveMinimum = false
public var maximum: T?
public var exclusiveMaximum = false
public var multipleOf: T?
}
public struct ArrayRule {
public var minItems: Int?
public var maxItems: Int?
public var uniqueItems: Bool
}
public enum StringValidationErrorKind: Error {
case minLength, maxLength, pattern
}
public enum NumericValidationErrorKind: Error {
case minimum, maximum, multipleOf
}
public enum ArrayValidationErrorKind: Error {
case minItems, maxItems, uniqueItems
}
public struct ValidationError<T: Error & Hashable>: Error {
public fileprivate(set) var kinds: Set<T>
}
public struct Validator {
/// Validate a string against a rule.
/// - Parameter string: The String you wish to validate.
/// - Parameter rule: The StringRule you wish to use for validation.
/// - Returns: A validated string.
/// - Throws: `ValidationError<StringValidationErrorKind>` if the string is invalid against the rule,
/// `NSError` if the rule.pattern is invalid.
public static func validate(_ string: String, against rule: StringRule) throws -> String {
var error = ValidationError<StringValidationErrorKind>(kinds: [])
if let minLength = rule.minLength, !(minLength <= string.count) {
error.kinds.insert(.minLength)
}
if let maxLength = rule.maxLength, !(string.count <= maxLength) {
error.kinds.insert(.maxLength)
}
if let pattern = rule.pattern {
let matches = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
.matches(in: string, range: .init(location: 0, length: string.utf16.count))
if matches.isEmpty {
error.kinds.insert(.pattern)
}
}
guard error.kinds.isEmpty else {
throw error
}
return string
}
/// Validate a integer against a rule.
/// - Parameter numeric: The integer you wish to validate.
/// - Parameter rule: The NumericRule you wish to use for validation.
/// - Returns: A validated integer.
/// - Throws: `ValidationError<NumericValidationErrorKind>` if the numeric is invalid against the rule.
public static func validate<T: Comparable & BinaryInteger>(_ numeric: T, against rule: NumericRule<T>) throws -> T {
var error = ValidationError<NumericValidationErrorKind>(kinds: [])
if let minium = rule.minimum {
if !rule.exclusiveMinimum, minium > numeric {
error.kinds.insert(.minimum)
}
if rule.exclusiveMinimum, minium >= numeric {
error.kinds.insert(.minimum)
}
}
if let maximum = rule.maximum {
if !rule.exclusiveMaximum, numeric > maximum {
error.kinds.insert(.maximum)
}
if rule.exclusiveMaximum, numeric >= maximum {
error.kinds.insert(.maximum)
}
}
if let multipleOf = rule.multipleOf, !numeric.isMultiple(of: multipleOf) {
error.kinds.insert(.multipleOf)
}
guard error.kinds.isEmpty else {
throw error
}
return numeric
}
/// Validate a fractional number against a rule.
/// - Parameter numeric: The fractional number you wish to validate.
/// - Parameter rule: The NumericRule you wish to use for validation.
/// - Returns: A validated fractional number.
/// - Throws: `ValidationError<NumericValidationErrorKind>` if the numeric is invalid against the rule.
public static func validate<T: Comparable & FloatingPoint>(_ numeric: T, against rule: NumericRule<T>) throws -> T {
var error = ValidationError<NumericValidationErrorKind>(kinds: [])
if let minium = rule.minimum {
if !rule.exclusiveMinimum, minium > numeric {
error.kinds.insert(.minimum)
}
if rule.exclusiveMinimum, minium >= numeric {
error.kinds.insert(.minimum)
}
}
if let maximum = rule.maximum {
if !rule.exclusiveMaximum, numeric > maximum {
error.kinds.insert(.maximum)
}
if rule.exclusiveMaximum, numeric >= maximum {
error.kinds.insert(.maximum)
}
}
if let multipleOf = rule.multipleOf, numeric.remainder(dividingBy: multipleOf) != 0 {
error.kinds.insert(.multipleOf)
}
guard error.kinds.isEmpty else {
throw error
}
return numeric
}
/// Validate a array against a rule.
/// - Parameter array: The Array you wish to validate.
/// - Parameter rule: The ArrayRule you wish to use for validation.
/// - Returns: A validated array.
/// - Throws: `ValidationError<ArrayValidationErrorKind>` if the string is invalid against the rule.
public static func validate(_ array: Array<AnyHashable>, against rule: ArrayRule) throws -> Array<AnyHashable> {
var error = ValidationError<ArrayValidationErrorKind>(kinds: [])
if let minItems = rule.minItems, !(minItems <= array.count) {
error.kinds.insert(.minItems)
}
if let maxItems = rule.maxItems, !(array.count <= maxItems) {
error.kinds.insert(.maxItems)
}
if rule.uniqueItems {
let unique = Set(array)
if unique.count != array.count {
error.kinds.insert(.uniqueItems)
}
}
guard error.kinds.isEmpty else {
throw error
}
return array
}
}

View File

@ -1,94 +0,0 @@
# Swift5 API client for PetstoreClient
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client.
- API version: 1.0.0
- Package version:
- Generator version: 7.9.0-SNAPSHOT
- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen
## Installation
### Carthage
Run `carthage update`
### CocoaPods
Run `pod install`
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetAPI* | [**addPet**](docs/PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store
*PetAPI* | [**deletePet**](docs/PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
*PetAPI* | [**findPetsByStatus**](docs/PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetAPI* | [**findPetsByTags**](docs/PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
*PetAPI* | [**getPetById**](docs/PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
*PetAPI* | [**updatePet**](docs/PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet
*PetAPI* | [**updatePetWithForm**](docs/PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetAPI* | [**uploadFile**](docs/PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreAPI* | [**getInventory**](docs/StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreAPI* | [**getOrderById**](docs/StoreAPI.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreAPI* | [**placeOrder**](docs/StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet
*UserAPI* | [**createUser**](docs/UserAPI.md#createuser) | **POST** /user | Create user
*UserAPI* | [**createUsersWithArrayInput**](docs/UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserAPI* | [**createUsersWithListInput**](docs/UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
*UserAPI* | [**deleteUser**](docs/UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user
*UserAPI* | [**getUserByName**](docs/UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name
*UserAPI* | [**loginUser**](docs/UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system
*UserAPI* | [**logoutUser**](docs/UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
*UserAPI* | [**updateUser**](docs/UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user
## Documentation For Models
- [ApiResponse](docs/ApiResponse.md)
- [Category](docs/Category.md)
- [Order](docs/Order.md)
- [Pet](docs/Pet.md)
- [Tag](docs/Tag.md)
- [User](docs/User.md)
<a id="documentation-for-authorization"></a>
## Documentation For Authorization
Authentication schemes defined for the API:
<a id="petstore_auth"></a>
### petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
<a id="api_key"></a>
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
<a id="auth_cookie"></a>
### auth_cookie
- **Type**: API key
- **API key parameter name**: AUTH_KEY
- **Location**:
## Author

View File

@ -1,12 +0,0 @@
# ApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **Int** | | [optional]
**type** | **String** | | [optional]
**message** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,11 +0,0 @@
# Category
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Int64** | | [optional]
**name** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,11 +0,0 @@
# InlineObject
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **String** | Updated name of the pet | [optional]
**status** | **String** | Updated status of the pet | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

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