diff --git a/Example/Sources/PetStore/CustomAuth.swift b/Example/Sources/PetStore/CustomAuth.swift index f2ab669..f8d9fff 100644 --- a/Example/Sources/PetStore/CustomAuth.swift +++ b/Example/Sources/PetStore/CustomAuth.swift @@ -8,9 +8,9 @@ protocol TokenCacheService { func clearToken() } -extension NetworkClient { +extension APIClient { - func bearerAuth(_ service: TokenCacheService) -> NetworkClient { + func bearerAuth(_ service: TokenCacheService) -> APIClient { // It's not required to create a .tokenCacheService config in this case, but it allows to override the token cache service and use it in other services, for instance, in a token refresher. configs(\.tokenCacheService, service) .auth( @@ -24,7 +24,7 @@ extension NetworkClient { } } -extension NetworkClient.Configs { +extension APIClient.Configs { var tokenCacheService: TokenCacheService { get { diff --git a/Example/Sources/PetStore/PetStore.swift b/Example/Sources/PetStore/PetStore.swift index 26b5ee0..cfe61e3 100644 --- a/Example/Sources/PetStore/PetStore.swift +++ b/Example/Sources/PetStore/PetStore.swift @@ -5,10 +5,10 @@ public struct PetStore { // MARK: - BaseURL - var client: NetworkClient + var client: APIClient public init(baseURL: BaseURL, fileID: String, line: UInt) { - client = NetworkClient(baseURL: baseURL.url) + client = APIClient(baseURL: baseURL.url) .fileIDLine(fileID: fileID, line: line) .bodyDecoder(PetStoreDecoder()) .tokenRefresher { client, _ in @@ -29,7 +29,7 @@ public extension PetStore { struct Pet { - var client: NetworkClient + var client: APIClient public func update(_ pet: PetModel) async throws -> PetModel { try await client.body(pet).put() @@ -53,7 +53,7 @@ public extension PetStore { public struct PetByID { - var client: NetworkClient + var client: APIClient public func get() async throws -> PetModel { try await client() @@ -90,7 +90,7 @@ public extension PetStore { struct Store { - var client: NetworkClient + var client: APIClient public func inventory() async throws -> [String: Int] { try await client("inventory").auth(enabled: true).call() @@ -106,7 +106,7 @@ public extension PetStore { public struct Order { - var client: NetworkClient + var client: APIClient public func find() async throws -> OrderModel { try await client() @@ -129,7 +129,7 @@ public extension PetStore { struct User { - var client: NetworkClient + var client: APIClient public func create(_ model: UserModel) async throws -> UserModel { try await client.body(model).post() @@ -155,7 +155,7 @@ public extension PetStore { public struct UserByUsername { - var client: NetworkClient + var client: APIClient public func get() async throws -> UserModel { try await client() diff --git a/Example/Sources/PetStore/TokenRefresher.swift b/Example/Sources/PetStore/TokenRefresher.swift index 3da347e..96a50db 100644 --- a/Example/Sources/PetStore/TokenRefresher.swift +++ b/Example/Sources/PetStore/TokenRefresher.swift @@ -8,9 +8,9 @@ protocol TokenRefresher { ) async throws -> (Data, HTTPURLResponse) } -extension NetworkClient { +extension APIClient { - func tokenRefresher(_ refresher: @escaping (NetworkClient.Configs) -> TokenRefresher) -> NetworkClient { + func tokenRefresher(_ refresher: @escaping (APIClient.Configs) -> TokenRefresher) -> APIClient { configs { configs in let base = configs.httpClient configs.httpClient = HTTPClient { request, configs in @@ -26,7 +26,7 @@ struct APITokenRefresher: TokenRefresher { let tokenService: TokenCacheService - init(_ configs: NetworkClient.Configs) { + init(_ configs: APIClient.Configs) { tokenService = configs.tokenCacheService } diff --git a/Package.swift b/Package.swift index bc53a2b..4b6841d 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription var package = Package( - name: "swift-networking", + name: "swift-api-client", platforms: [ .macOS(.v10_15), .iOS(.v13), @@ -12,21 +12,21 @@ var package = Package( .tvOS(.v13), ], products: [ - .library(name: "SwiftNetworking", targets: ["SwiftNetworking"]), + .library(name: "SwiftAPIClient", targets: ["SwiftAPIClient"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-log.git", from: "1.5.3"), ], targets: [ .target( - name: "SwiftNetworking", + name: "SwiftAPIClient", dependencies: [ .product(name: "Logging", package: "swift-log"), ] ), .testTarget( - name: "SwiftNetworkingTests", - dependencies: [.target(name: "SwiftNetworking")] + name: "SwiftAPIClientTests", + dependencies: [.target(name: "SwiftAPIClient")] ), ] ) diff --git a/README.md b/README.md index 47a99ae..b478086 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,23 @@ -`swift-networking` is a comprehensive and modular client networking library for Swift. +`swift-api-client` is a comprehensive and modular Swift library for API design. ## Table of Contents - [Table of Contents](#table-of-contents) - [Main Goals of the Library](#main-goals-of-the-library) - [Usage](#usage) -- [What is `NetworkClient`](#what-is-networkclient) -- [Built-in `NetworkClient` Extensions](#built-in-networkclient-extensions) +- [What is `APIClient`](#what-is-apiclient) +- [Built-in `APIClient` Extensions](#built-in-apiclient-extensions) - [Request building](#request-building) - [Request execution](#request-execution) - - [`NetworkClientCaller`](#networkclientcaller) + - [`APIClientCaller`](#apiclientcaller) - [Serializer](#serializer) - [Encoding and Decoding](#encoding-and-decoding) - [ContentSerializer](#contentserializer) - [Auth](#auth) - [Mocking](#mocking) - [Logging](#logging) -- [`NetworkClient.Configs`](#networkclientconfigs) +- [`APIClient.Configs`](#apiclientconfigs) - [Configs Modifications Order](#configs-modifications-order) -- [Introducing `swift-networking-addons`](#introducing-swift-networking-addons) +- [Introducing `swift-api-client-addons`](#introducing-swift-api-client-addons) - [Installation](#installation) - [Author](#author) - [License](#license) @@ -31,19 +31,19 @@ - Facilitation of testing and mocking. ## Usage -The core of the library is the `NetworkClient` struct, serving both as a request builder and executor. It is a generic struct, enabling use for any task associated with `URLRequest`. +The core of the library is the `APIClient` struct, serving both as a request builder and executor. It is a generic struct, enabling use for any task associated with `URLRequest`. -The branching and configuration injection/overriding capabilities of NetworkClient, extending to all its child instances, facilitate the effortless recycling of networking logic and tasks, thereby eliminating the need for copy-pasting. +The branching and configuration injection/overriding capabilities of APIClient, extending to all its child instances, facilitate the effortless recycling of networking logic and tasks, thereby eliminating the need for copy-pasting. While a full example is available in the [Example folder](/Example/), here is a simple usage example: ```swift -let client = NetworkClient(url: baseURL) +let client = APIClient(url: baseURL) .auth(.bearer(token)) .bodyDecoder(.json(dateDecodingStrategy: .iso8601)) .bodyEncoder(.json(dateEncodingStrategy: .iso8601)) .errorDecoder(.decodable(APIError.self)) -// Create a `NetworkClient` instance for the /users path +// Create a `APIClient` instance for the /users path let usersClient = client("users") // GET /users?name=John&limit=1 @@ -52,7 +52,7 @@ let john: User = try await usersClient .auth(enabled: false) .get() -// Create a `NetworkClient` instance for /users/{userID} path +// Create a `APIClient` instance for /users/{userID} path let johnClient = usersClient(john.id) // GET /user/{userID} @@ -65,9 +65,9 @@ try await johnClient.body(updatedUser).put() try await johnClient.delete() ``` -## What is `NetworkClient` +## What is `APIClient` -`NetworkClient` is a struct combining a closure for creating a URLRequest and a typed dictionary of configurations `NetworkClient.Configs`. There are two primary ways to extend a `NetworkClient`: +`APIClient` is a struct combining a closure for creating a URLRequest and a typed dictionary of configurations `APIClient.Configs`. There are two primary ways to extend a `APIClient`: - `modifyRequest` modifiers. - `configs` modifiers. @@ -75,17 +75,17 @@ Executing an operation on the client involves: - `withRequest` methods. All built-in extensions utilize these modifiers. -## Built-in `NetworkClient` Extensions +## Built-in `APIClient` Extensions ### Request building Numerous methods exist for modifying a `URLRequest` such as `query`, `body`, `header`, `headers`, `method`, `path`, `timeout`, `cachePolicy`, `body`, `bodyStream` and more.\ -The full list of modifiers is available in [RequestModifiers.swift](/Sources/SwiftNetworking/Modifiers/RequestModifiers.swift), all based on the `modifyRequest` modifier. +The full list of modifiers is available in [RequestModifiers.swift](/Sources/SwiftAPIClient/Modifiers/RequestModifiers.swift), all based on the `modifyRequest` modifier. Notable non-obvious modifiers include: - `.callAsFunction(path...)` - as a shorthand for the `.path(path...)` modifier, allowing `client("path")` instead of `client.path("path")`. - HTTP method shorthands like `.get`, `.post`, `.put`, `.delete`, `.patch`. ### Request execution -The method`call(_ caller: NetworkClientCaller<...>, as serializer: Serializer<...>)` is provided. +The method`call(_ caller: APIClientCaller<...>, as serializer: Serializer<...>)` is provided. Examples: ```swift try await client.call(.http, as: .decodable) @@ -96,7 +96,7 @@ There are also shorthands for built-in callers and serializers: - `call()` is equivalent to `call(.http, as: .decodable)` or `call(.http, as: .void)` - `callAsFunction()` acts as `call()`, simplifying `client.delete()` to `client.delete.call()` or `client()` instead of `client.call()`, etc. -#### `NetworkClientCaller` +#### `APIClientCaller` Defines request execution with several built-in callers for various request types, including: - `.http` for HTTP requests using `try await` syntax. - `.httpPublisher` for HTTP requests with Combine syntax. @@ -113,7 +113,7 @@ Custom callers can be created for different types of requests, such as WebSocket - `.decodable` for decoding a response into a Decodable type. - `.data` for obtaining a raw Data response. - `.void` for ignoring the response. -- `.instance` for receiving a response of the same type as `NetworkClientCaller` returns. For HTTP requests, it is `Data`. +- `.instance` for receiving a response of the same type as `APIClientCaller` returns. For HTTP requests, it is `Data`. The `.decodable` serializer uses the `.bodyDecoder` configuration, which can be customized with the `.bodyDecoder` modifier. The default `bodyDecoder` is `JSONDecoder()`. @@ -146,12 +146,12 @@ Built-in tools for mocking requests include: - `.usingMocksPolicy` configuration defines whether to use mocks, customizable with `.usingMocks(policy:)` modifier. By default, mocks are ignored in the `live` environment and used as specified for tests and SwiftUI previews. -Additionally, `.mock(_:)` as a `NetworkClientCaller` offers an alternative way to mock requests, like `client.call(.mock(data), as: .decodable)`. +Additionally, `.mock(_:)` as a `APIClientCaller` offers an alternative way to mock requests, like `client.call(.mock(data), as: .decodable)`. Custom HTTPClient instances can also be created and injected for testing or previews. ### Logging -`swift-networking` employs `swift-log` for logging, with `.logger` and `.logLevel` configurations customizable via `logger` and `.log(level:)` modifiers. +`swift-api-client` employs `swift-log` for logging, with `.logger` and `.logLevel` configurations customizable via `logger` and `.log(level:)` modifiers. The default log level is `.info`. A built-in `.none` Logger is available to disable all logs. Log example: @@ -166,13 +166,13 @@ Content-Type: application/json ``` Log message format can be customized with the `.loggingComponents(_:)` modifier. -## `NetworkClient.Configs` +## `APIClient.Configs` A collection of config values is propagated through the modifier chain. These configs are accessible in all core methods: `modifyRequest`, `withRequest`, and `withConfigs`. -To create custom config values, extend the `NetworkClient.Configs` structure with a new property. +To create custom config values, extend the `APIClient.Configs` structure with a new property. Use subscript with your property key path to get and set the value, and provide a dedicated modifier for clients to use when setting this value: ```swift -extension NetworkClient.Configs { +extension APIClient.Configs { var myCustomValue: MyConfig { get { self[\.myCustomValue] ?? myDefaultConfig @@ -183,8 +183,8 @@ extension NetworkClient.Configs { } } -extension NetworkClient { - func myCustomValue(_ myCustomValue: MyConfig) -> NetworkClient { +extension APIClient { + func myCustomValue(_ myCustomValue: MyConfig) -> APIClient { configs(\.myCustomValue, myCustomValue) } } @@ -215,10 +215,10 @@ let configs = try client print(configs.intValue) // 3 ``` -## Introducing `swift-networking-addons` +## Introducing `swift-api-client-addons` -To enhance your experience with `swift-networking`, I'm excited to introduce [`swift-networking-addons`](https://github.com/dankinsoid/swift-networking-addons) -— a complementary library designed to extend the core functionality of `swift-networking` with additional features and utilities. +To enhance your experience with `swift-api-client`, I'm excited to introduce [`swift-api-client-addons`](https://github.com/dankinsoid/swift-api-client-addons) +— a complementary library designed to extend the core functionality of `swift-api-client` with additional features and utilities. ## Installation @@ -232,13 +232,13 @@ import PackageDescription let package = Package( name: "SomeProject", dependencies: [ - .package(url: "https://github.com/dankinsoid/swift-networking.git", from: "0.38.0") + .package(url: "https://github.com/dankinsoid/swift-api-client.git", from: "0.39.0") ], targets: [ .target( name: "SomeProject", dependencies: [ - .product(name: "SwiftNetworking", package: "swift-networking"), + .product(name: "SwiftAPIClient", package: "swift-api-client"), ] ) ] @@ -254,7 +254,7 @@ Daniil Voidilov, voidilov@gmail.com ## License -swift-networking is available under the MIT license. See the LICENSE file for more info. +swift-api-client is available under the MIT license. See the LICENSE file for more info. ## Contributing We welcome contributions to Swift-Networking! Please read our contributing guidelines to get started. diff --git a/Sources/SwiftNetworking/NetworkClient.swift b/Sources/SwiftAPIClient/APIClient.swift similarity index 90% rename from Sources/SwiftNetworking/NetworkClient.swift rename to Sources/SwiftAPIClient/APIClient.swift index 9da91d9..9c79c05 100644 --- a/Sources/SwiftNetworking/NetworkClient.swift +++ b/Sources/SwiftAPIClient/APIClient.swift @@ -4,7 +4,7 @@ import Foundation #endif /// A network client for handling url requests with configurable request and configuration handling. -public struct NetworkClient { +public struct APIClient { private var _createRequest: (Configs) throws -> URLRequest private var modifyConfigs: (inout Configs) -> Void = { _ in } @@ -49,8 +49,8 @@ public struct NetworkClient { /// - Parameters: /// - keyPath: The key path to the configuration property to be modified. /// - value: The new value for the specified configuration property. - /// - Returns: An instance of `NetworkClient` with updated configurations. - public func configs(_ keyPath: WritableKeyPath, _ value: T) -> NetworkClient { + /// - Returns: An instance of `APIClient` with updated configurations. + public func configs(_ keyPath: WritableKeyPath, _ value: T) -> APIClient { configs { $0[keyPath: keyPath] = value } @@ -58,8 +58,8 @@ public struct NetworkClient { /// Configures the client with a closure that modifies its configurations. /// - Parameter configs: A closure that takes `inout Configs` and modifies them. - /// - Returns: An instance of `NetworkClient` with updated configurations. - public func configs(_ configs: @escaping (inout Configs) -> Void) -> NetworkClient { + /// - Returns: An instance of `APIClient` with updated configurations. + public func configs(_ configs: @escaping (inout Configs) -> Void) -> APIClient { var result = self result.modifyConfigs = { [modifyConfigs] in modifyConfigs(&$0) @@ -71,10 +71,10 @@ public struct NetworkClient { /// Modifies the URLRequest using the provided closure. /// - location: When the request should be modified. /// - modifier: A closure that takes `inout URLRequest` and modifies the URLRequest. - /// - Returns: An instance of `NetworkClient` with a modified URLRequest. + /// - Returns: An instance of `APIClient` with a modified URLRequest. public func modifyRequest( _ modifier: @escaping (inout URLRequest) throws -> Void - ) -> NetworkClient { + ) -> APIClient { modifyRequest { req, _ in try modifier(&req) } @@ -84,10 +84,10 @@ public struct NetworkClient { /// - Parameter: /// - location: When the request should be modified. /// - modifier: A closure that takes `inout URLRequest` and `Configs`, and modifies the URLRequest. - /// - Returns: An instance of `NetworkClient` with a modified URLRequest. + /// - Returns: An instance of `APIClient` with a modified URLRequest. public func modifyRequest( _ modifier: @escaping (inout URLRequest, Configs) throws -> Void - ) -> NetworkClient { + ) -> APIClient { var result = self result._createRequest = { [_createRequest] configs in var request = try _createRequest(configs) diff --git a/Sources/SwiftNetworking/NetworkClientConfigs.swift b/Sources/SwiftAPIClient/APIClientConfigs.swift similarity index 80% rename from Sources/SwiftNetworking/NetworkClientConfigs.swift rename to Sources/SwiftAPIClient/APIClientConfigs.swift index 6aa1044..a7f0b42 100644 --- a/Sources/SwiftNetworking/NetworkClientConfigs.swift +++ b/Sources/SwiftAPIClient/APIClientConfigs.swift @@ -4,21 +4,21 @@ import Logging import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { - /// A struct representing the configuration settings for a `NetworkClient`. + /// A struct representing the configuration settings for a `APIClient`. struct Configs { - private var values: [PartialKeyPath: Any] = [:] + private var values: [PartialKeyPath: Any] = [:] - /// Initializes a new configuration set for `NetworkClient`. + /// Initializes a new configuration set for `APIClient`. public init() { } /// Provides subscript access to configuration values based on their key paths. /// - Parameter keyPath: A `WritableKeyPath` to the configuration property. /// - Returns: The value of the configuration property if it exists, or `nil` otherwise. - public subscript(_ keyPath: WritableKeyPath) -> T? { + public subscript(_ keyPath: WritableKeyPath) -> T? { get { values[keyPath] as? T } set { values[keyPath] = newValue } } @@ -26,7 +26,7 @@ public extension NetworkClient { /// Provides subscript access to configuration values based on their key paths. /// - Parameter keyPath: A `WritableKeyPath` to the configuration property. /// - Returns: The value of the configuration property if it exists, or `nil` otherwise. - public subscript(_ keyPath: WritableKeyPath) -> T? { + public subscript(_ keyPath: WritableKeyPath) -> T? { get { values[keyPath] as? T } set { values[keyPath] = newValue } } @@ -36,7 +36,7 @@ public extension NetworkClient { /// - keyPath: A `WritableKeyPath` to the configuration property to be modified. /// - value: The new value to set for the specified configuration property. /// - Returns: A new `Configs` instance with the updated configuration setting. - public func with(_ keyPath: WritableKeyPath, _ value: T) -> NetworkClient.Configs { + public func with(_ keyPath: WritableKeyPath, _ value: T) -> APIClient.Configs { var result = self result[keyPath: keyPath] = value return result diff --git a/Sources/SwiftNetworking/Clients/HTTPClient.swift b/Sources/SwiftAPIClient/Clients/HTTPClient.swift similarity index 70% rename from Sources/SwiftNetworking/Clients/HTTPClient.swift rename to Sources/SwiftAPIClient/Clients/HTTPClient.swift index 742daec..021c63e 100644 --- a/Sources/SwiftNetworking/Clients/HTTPClient.swift +++ b/Sources/SwiftAPIClient/Clients/HTTPClient.swift @@ -7,26 +7,26 @@ import FoundationNetworking public struct HTTPClient { /// A closure that asynchronously retrieves data and an HTTP response for a given URLRequest and network configurations. - public var data: (URLRequest, NetworkClient.Configs) async throws -> (Data, HTTPURLResponse) + public var data: (URLRequest, APIClient.Configs) async throws -> (Data, HTTPURLResponse) /// Initializes a new `HTTPClient` with a custom data retrieval closure. - /// - Parameter data: A closure that takes a `URLRequest` and `NetworkClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. - public init(_ data: @escaping (URLRequest, NetworkClient.Configs) async throws -> (Data, HTTPURLResponse)) { + /// - Parameter data: A closure that takes a `URLRequest` and `APIClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. + public init(_ data: @escaping (URLRequest, APIClient.Configs) async throws -> (Data, HTTPURLResponse)) { self.data = data } } -public extension NetworkClient { +public extension APIClient { /// Sets a custom HTTP client for the network client. /// - Parameter client: The `HTTPClient` to be used for network requests. - /// - Returns: An instance of `NetworkClient` configured with the specified HTTP client. - func httpClient(_ client: HTTPClient) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified HTTP client. + func httpClient(_ client: HTTPClient) -> APIClient { configs(\.httpClient, client) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The HTTP client used for network operations. /// Gets the currently set `HTTPClient`, or the default `URLsession`-based client if not set. @@ -37,9 +37,9 @@ public extension NetworkClient.Configs { } } -public extension NetworkClientCaller where Result == AsyncValue, Response == Data { +public extension APIClientCaller where Result == AsyncValue, Response == Data { - static var http: NetworkClientCaller { + static var http: APIClientCaller { .http { request, configs in var request = request if request.httpMethod == nil { @@ -53,11 +53,11 @@ public extension NetworkClientCaller where Result == AsyncValue, Response } } -extension NetworkClientCaller where Result == AsyncValue, Response == Data { +extension APIClientCaller where Result == AsyncValue, Response == Data { static func http( - task: @escaping @Sendable (URLRequest, NetworkClient.Configs) async throws -> (Data, HTTPURLResponse) - ) -> NetworkClientCaller { + task: @escaping @Sendable (URLRequest, APIClient.Configs) async throws -> (Data, HTTPURLResponse) + ) -> APIClientCaller { .http(task: task) { try $2.httpResponseValidator.validate($1, $0, $2) } data: { @@ -66,14 +66,14 @@ extension NetworkClientCaller where Result == AsyncValue, Response == Dat } } -extension NetworkClientCaller where Result == AsyncValue { +extension APIClientCaller where Result == AsyncValue { static func http( - task: @escaping @Sendable (URLRequest, NetworkClient.Configs) async throws -> (Response, HTTPURLResponse), - validate: @escaping (Response, HTTPURLResponse, NetworkClient.Configs) throws -> Void, + task: @escaping @Sendable (URLRequest, APIClient.Configs) async throws -> (Response, HTTPURLResponse), + validate: @escaping (Response, HTTPURLResponse, APIClient.Configs) throws -> Void, data: @escaping (Response) -> Data? - ) -> NetworkClientCaller { - NetworkClientCaller { uuid, request, configs, serialize in + ) -> APIClientCaller { + APIClientCaller { uuid, request, configs, serialize in { let value: Response let response: HTTPURLResponse diff --git a/Sources/SwiftNetworking/Clients/HTTPDownloadClient.swift b/Sources/SwiftAPIClient/Clients/HTTPDownloadClient.swift similarity index 65% rename from Sources/SwiftNetworking/Clients/HTTPDownloadClient.swift rename to Sources/SwiftAPIClient/Clients/HTTPDownloadClient.swift index cc1f074..9c70123 100644 --- a/Sources/SwiftNetworking/Clients/HTTPDownloadClient.swift +++ b/Sources/SwiftAPIClient/Clients/HTTPDownloadClient.swift @@ -6,28 +6,28 @@ import FoundationNetworking public struct HTTPDownloadClient { /// A closure that asynchronously retrieves data and an HTTP response for a given URLRequest and network configurations. - public var download: (URLRequest, NetworkClient.Configs) async throws -> (URL, HTTPURLResponse) + public var download: (URLRequest, APIClient.Configs) async throws -> (URL, HTTPURLResponse) /// Initializes a new `HTTPUploadClient` with a custom data retrieval closure. - /// - Parameter data: A closure that takes a `URLRequest` and `NetworkClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. + /// - Parameter data: A closure that takes a `URLRequest` and `APIClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. public init( - _ download: @escaping (URLRequest, NetworkClient.Configs) async throws -> (URL, HTTPURLResponse)) + _ download: @escaping (URLRequest, APIClient.Configs) async throws -> (URL, HTTPURLResponse)) { self.download = download } } -public extension NetworkClient { +public extension APIClient { /// Sets a custom HTTP download client for the network client. /// - Parameter client: The `HTTPDownloadClient` to be used for network requests. - /// - Returns: An instance of `NetworkClient` configured with the specified HTTP client. - func httpDownloadClient(_ client: HTTPDownloadClient) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified HTTP client. + func httpDownloadClient(_ client: HTTPDownloadClient) -> APIClient { configs(\.httpDownloadClient, client) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The HTTP client used for network download operations. /// Gets the currently set `HTTPDownloadClient`, or the default `URLsession`-based client if not set. @@ -38,9 +38,9 @@ public extension NetworkClient.Configs { } } -public extension NetworkClientCaller where Result == AsyncValue, Response == URL { +public extension APIClientCaller where Result == AsyncValue, Response == URL { - static var httpDownload: NetworkClientCaller { + static var httpDownload: APIClientCaller { .http { request, configs in var request = request if request.httpMethod == nil { diff --git a/Sources/SwiftAPIClient/Clients/HTTPPublisher.swift b/Sources/SwiftAPIClient/Clients/HTTPPublisher.swift new file mode 100644 index 0000000..df4eace --- /dev/null +++ b/Sources/SwiftAPIClient/Clients/HTTPPublisher.swift @@ -0,0 +1,16 @@ +#if canImport(Combine) +import Combine +import Foundation + +public extension APIClientCaller where Result == AnyPublisher, Response == Data { + + static var httpPublisher: APIClientCaller { + APIClientCaller>.http.map { value in + Publishers.Task { + try await value() + } + .eraseToAnyPublisher() + } + } +} +#endif diff --git a/Sources/SwiftNetworking/Clients/HTTPUploadClient.swift b/Sources/SwiftAPIClient/Clients/HTTPUploadClient.swift similarity index 68% rename from Sources/SwiftNetworking/Clients/HTTPUploadClient.swift rename to Sources/SwiftAPIClient/Clients/HTTPUploadClient.swift index 8bfcdda..49922e5 100644 --- a/Sources/SwiftNetworking/Clients/HTTPUploadClient.swift +++ b/Sources/SwiftAPIClient/Clients/HTTPUploadClient.swift @@ -6,12 +6,12 @@ import FoundationNetworking public struct HTTPUploadClient { /// A closure that asynchronously retrieves data and an HTTP response for a given URLRequest and network configurations. - public var upload: (URLRequest, UploadTask, NetworkClient.Configs) async throws -> (Data, HTTPURLResponse) + public var upload: (URLRequest, UploadTask, APIClient.Configs) async throws -> (Data, HTTPURLResponse) /// Initializes a new `HTTPUploadClient` with a custom data retrieval closure. - /// - Parameter data: A closure that takes a `URLRequest` and `NetworkClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. + /// - Parameter data: A closure that takes a `URLRequest` and `APIClient.Configs`, then asynchronously returns `Data` and an `HTTPURLResponse`. public init( - _ upload: @escaping (URLRequest, UploadTask, NetworkClient.Configs) async throws -> (Data, HTTPURLResponse)) + _ upload: @escaping (URLRequest, UploadTask, APIClient.Configs) async throws -> (Data, HTTPURLResponse)) { self.upload = upload } @@ -24,17 +24,17 @@ public enum UploadTask: Equatable { case stream } -public extension NetworkClient { +public extension APIClient { /// Sets a custom HTTP upload client for the network client. /// - Parameter client: The `HTTPUploadClient` to be used for network requests. - /// - Returns: An instance of `NetworkClient` configured with the specified HTTP client. - func httpUploadClient(_ client: HTTPUploadClient) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified HTTP client. + func httpUploadClient(_ client: HTTPUploadClient) -> APIClient { configs(\.httpUploadClient, client) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The HTTP client used for upload network operations. /// Gets the currently set `HTTPUploadClient`, or the default `URLsession`-based client if not set. @@ -45,9 +45,9 @@ public extension NetworkClient.Configs { } } -public extension NetworkClientCaller where Result == AsyncValue, Response == Data { +public extension APIClientCaller where Result == AsyncValue, Response == Data { - static func httpUpload(_ task: UploadTask = .stream) -> NetworkClientCaller { + static func httpUpload(_ task: UploadTask = .stream) -> APIClientCaller { .http { request, configs in var request = request if request.httpMethod == nil { diff --git a/Sources/SwiftNetworking/Clients/NetworkClientCaller.swift b/Sources/SwiftAPIClient/Clients/NetworkClientCaller.swift similarity index 83% rename from Sources/SwiftNetworking/Clients/NetworkClientCaller.swift rename to Sources/SwiftAPIClient/Clients/NetworkClientCaller.swift index 925a18f..ebc9a68 100644 --- a/Sources/SwiftNetworking/Clients/NetworkClientCaller.swift +++ b/Sources/SwiftAPIClient/Clients/NetworkClientCaller.swift @@ -5,17 +5,17 @@ import FoundationNetworking #endif /// A generic structure for handling network requests and their responses. -public struct NetworkClientCaller { +public struct APIClientCaller { private let _call: ( UUID, URLRequest, - NetworkClient.Configs, + APIClient.Configs, @escaping (Response, () throws -> Void) throws -> Value ) throws -> Result private let _mockResult: (_ value: Value) throws -> Result - /// Initializes a new `NetworkClientCaller`. + /// Initializes a new `APIClientCaller`. /// - Parameters: /// - call: A closure that performs the network call. /// - mockResult: A closure that handles mock results. @@ -23,7 +23,7 @@ public struct NetworkClientCaller { call: @escaping ( _ uuid: UUID, _ request: URLRequest, - _ configs: NetworkClient.Configs, + _ configs: APIClient.Configs, _ serialize: @escaping (Response, _ validate: () throws -> Void) throws -> Value ) throws -> Result, mockResult: @escaping (_ value: Value) throws -> Result @@ -41,7 +41,7 @@ public struct NetworkClientCaller { public func call( uuid: UUID, request: URLRequest, - configs: NetworkClient.Configs, + configs: APIClient.Configs, serialize: @escaping (Response, _ validate: () throws -> Void) throws -> Value ) throws -> Result { try _call(uuid, request, configs, serialize) @@ -56,14 +56,14 @@ public struct NetworkClientCaller { /// Maps the result to another type using the provided mapper. /// - Parameter mapper: A closure that maps the result to a different type. - /// - Returns: A `NetworkClientCaller` with the mapped result type. + /// - Returns: A `APIClientCaller` with the mapped result type. /// /// Example /// ```swift /// try await client.call(.http, as: .decodable) /// ``` - public func map(_ mapper: @escaping (Result) throws -> T) -> NetworkClientCaller { - NetworkClientCaller { + public func map(_ mapper: @escaping (Result) throws -> T) -> APIClientCaller { + APIClientCaller { try mapper(_call($0, $1, $2, $3)) } mockResult: { try mapper(_mockResult($0)) @@ -71,11 +71,11 @@ public struct NetworkClientCaller { } } -public extension NetworkClientCaller where Result == Value { +public extension APIClientCaller where Result == Value { /// A caller with a mocked response. - static func mock(_ response: Response) -> NetworkClientCaller { - NetworkClientCaller { _, _, _, serialize in + static func mock(_ response: Response) -> APIClientCaller { + APIClientCaller { _, _, _, serialize in try serialize(response) {} } mockResult: { value in value @@ -83,11 +83,11 @@ public extension NetworkClientCaller where Result == Value { } } -public extension NetworkClient { +public extension APIClient { /// Asynchronously performs a network call using the provided caller and serializer. /// - Parameters: - /// - caller: A `NetworkClientCaller` instance. + /// - caller: A `APIClientCaller` instance. /// - serializer: A `Serializer` to process the response. /// - Returns: The result of the network call. /// @@ -96,7 +96,7 @@ public extension NetworkClient { /// let value: SomeModel = try await client.call(.http, as: .decodable) /// ``` func call( - _ caller: NetworkClientCaller>, + _ caller: APIClientCaller>, as serializer: Serializer, fileID: String = #fileID, line: UInt = #line @@ -130,7 +130,7 @@ public extension NetworkClient { /// Performs a synchronous network call using the provided caller and serializer. /// - Parameters: - /// - caller: A `NetworkClientCaller` instance. + /// - caller: A `APIClientCaller` instance. /// - serializer: A `Serializer` to process the response. /// - Returns: The result of the network call. /// @@ -139,7 +139,7 @@ public extension NetworkClient { /// try client.call(.httpPublisher, as: .decodable).sink { ... } /// ``` func call( - _ caller: NetworkClientCaller, + _ caller: APIClientCaller, as serializer: Serializer, fileID: String = #fileID, line: UInt = #line @@ -191,9 +191,9 @@ public extension NetworkClient { /// Sets a closure to be executed before making a network call. /// /// - Parameters: - /// - closure: The closure to be executed before making a network call. It takes in an `inout URLRequest` and `NetworkClient.Configs` as parameters and can modify the request. - /// - Returns: The `NetworkClient` instance. - func beforeCall(_ closure: @escaping (inout URLRequest, NetworkClient.Configs) throws -> Void) -> NetworkClient { + /// - closure: The closure to be executed before making a network call. It takes in an `inout URLRequest` and `APIClient.Configs` as parameters and can modify the request. + /// - Returns: The `APIClient` instance. + func beforeCall(_ closure: @escaping (inout URLRequest, APIClient.Configs) throws -> Void) -> APIClient { configs { let beforeCall = $0.beforeCall $0.beforeCall = { request, configs in @@ -204,9 +204,9 @@ public extension NetworkClient { } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { - var beforeCall: (inout URLRequest, NetworkClient.Configs) throws -> Void { + var beforeCall: (inout URLRequest, APIClient.Configs) throws -> Void { get { self[\.beforeCall] ?? { _, _ in } } set { self[\.beforeCall] = newValue } } diff --git a/Sources/SwiftNetworking/Clients/URLSession+Client.swift b/Sources/SwiftAPIClient/Clients/URLSession+Client.swift similarity index 100% rename from Sources/SwiftNetworking/Clients/URLSession+Client.swift rename to Sources/SwiftAPIClient/Clients/URLSession+Client.swift diff --git a/Sources/SwiftNetworking/Extensions/Async++.swift b/Sources/SwiftAPIClient/Extensions/Async++.swift similarity index 100% rename from Sources/SwiftNetworking/Extensions/Async++.swift rename to Sources/SwiftAPIClient/Extensions/Async++.swift diff --git a/Sources/SwiftNetworking/Extensions/URLResponse++.swift b/Sources/SwiftAPIClient/Extensions/URLResponse++.swift similarity index 100% rename from Sources/SwiftNetworking/Extensions/URLResponse++.swift rename to Sources/SwiftAPIClient/Extensions/URLResponse++.swift diff --git a/Sources/SwiftNetworking/Modifiers/AuthModifier.swift b/Sources/SwiftAPIClient/Modifiers/AuthModifier.swift similarity index 89% rename from Sources/SwiftNetworking/Modifiers/AuthModifier.swift rename to Sources/SwiftAPIClient/Modifiers/AuthModifier.swift index c2bb551..a6db5e4 100644 --- a/Sources/SwiftNetworking/Modifiers/AuthModifier.swift +++ b/Sources/SwiftAPIClient/Modifiers/AuthModifier.swift @@ -3,7 +3,7 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// Indicates whether authentication is enabled for network requests. var isAuthEnabled: Bool { @@ -12,12 +12,12 @@ public extension NetworkClient.Configs { } } -public extension NetworkClient { +public extension APIClient { /// Configures the network client with a custom authentication modifier. /// - Parameter authModifier: An `AuthModifier` that modifies the request for authentication. - /// - Returns: An instance of `NetworkClient` configured with the specified authentication modifier. - func auth(_ authModifier: AuthModifier) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified authentication modifier. + func auth(_ authModifier: AuthModifier) -> APIClient { modifyRequest { request, configs in if configs.isAuthEnabled { try authModifier.modifier(&request, configs) @@ -27,8 +27,8 @@ public extension NetworkClient { /// Enables or disables authentication for the network client. /// - Parameter enabled: A Boolean value indicating whether to enable authentication. - /// - Returns: An instance of `NetworkClient` with authentication set as specified. - func auth(enabled: Bool) -> NetworkClient { + /// - Returns: An instance of `APIClient` with authentication set as specified. + func auth(enabled: Bool) -> APIClient { configs(\.isAuthEnabled, enabled) } } @@ -37,11 +37,11 @@ public extension NetworkClient { public struct AuthModifier { /// A closure that modifies a `URLRequest` for authentication. - public let modifier: (inout URLRequest, NetworkClient.Configs) throws -> Void + public let modifier: (inout URLRequest, APIClient.Configs) throws -> Void /// Initializes a new `AuthModifier` with a custom modifier closure. - /// - Parameter modifier: A closure that modifies a `URLRequest` and `NetworkClient.Configs` for authentication. - public init(modifier: @escaping (inout URLRequest, NetworkClient.Configs) throws -> Void) { + /// - Parameter modifier: A closure that modifies a `URLRequest` and `APIClient.Configs` for authentication. + public init(modifier: @escaping (inout URLRequest, APIClient.Configs) throws -> Void) { self.modifier = modifier } diff --git a/Sources/SwiftNetworking/Modifiers/CodersModifiers.swift b/Sources/SwiftAPIClient/Modifiers/CodersModifiers.swift similarity index 81% rename from Sources/SwiftNetworking/Modifiers/CodersModifiers.swift rename to Sources/SwiftAPIClient/Modifiers/CodersModifiers.swift index f7496ef..cb9067c 100644 --- a/Sources/SwiftNetworking/Modifiers/CodersModifiers.swift +++ b/Sources/SwiftAPIClient/Modifiers/CodersModifiers.swift @@ -3,14 +3,14 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { /// Sets a request body encoder. /// /// - Parameter encoder: A request body encoder. /// /// - Returns: A new network client with the request body encoder. - func bodyEncoder(_ encoder: some ContentEncoder) -> NetworkClient { + func bodyEncoder(_ encoder: some ContentEncoder) -> APIClient { configs(\.bodyEncoder, encoder) } @@ -19,7 +19,7 @@ public extension NetworkClient { /// - Parameter decoder: A response body decoder. /// /// - Returns: A new network client with the response body decoder. - func bodyDecoder(_ decoder: some DataDecoder) -> NetworkClient { + func bodyDecoder(_ decoder: some DataDecoder) -> APIClient { configs(\.bodyDecoder, decoder) } @@ -28,12 +28,12 @@ public extension NetworkClient { /// - Parameter encoder: A request query encoder. /// /// - Returns: A new network client with the request query encoder. - func queryEncoder(_ encoder: some QueryEncoder) -> NetworkClient { + func queryEncoder(_ encoder: some QueryEncoder) -> APIClient { configs(\.queryEncoder, encoder) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// A request body encoder. var bodyEncoder: any ContentEncoder { diff --git a/Sources/SwiftNetworking/Modifiers/ErrorDecodeModifiers.swift b/Sources/SwiftAPIClient/Modifiers/ErrorDecodeModifiers.swift similarity index 73% rename from Sources/SwiftNetworking/Modifiers/ErrorDecodeModifiers.swift rename to Sources/SwiftAPIClient/Modifiers/ErrorDecodeModifiers.swift index fedd491..0271a3a 100644 --- a/Sources/SwiftNetworking/Modifiers/ErrorDecodeModifiers.swift +++ b/Sources/SwiftAPIClient/Modifiers/ErrorDecodeModifiers.swift @@ -1,6 +1,6 @@ import Foundation -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The error decoder used to decode errors from network responses. /// Gets the currently set `ErrorDecoder`, or `.none` if not set. @@ -11,17 +11,17 @@ public extension NetworkClient.Configs { } } -public extension NetworkClient { +public extension APIClient { /// Use this modifier when you want the client to throw an error that is decoded from the response. /// - Parameter decoder: The `ErrorDecoder` to be used for decoding errors. - /// - Returns: An instance of `NetworkClient` configured with the specified error decoder. + /// - Returns: An instance of `APIClient` configured with the specified error decoder. /// /// Example usage: /// ```swift /// client.errorDecoder(.decodable(ErrorResponse.self)) /// ``` - func errorDecoder(_ decoder: ErrorDecoder) -> NetworkClient { + func errorDecoder(_ decoder: ErrorDecoder) -> APIClient { configs(\.errorDecoder, decoder) } } diff --git a/Sources/SwiftNetworking/Modifiers/FileIDLine.swift b/Sources/SwiftAPIClient/Modifiers/FileIDLine.swift similarity index 80% rename from Sources/SwiftNetworking/Modifiers/FileIDLine.swift rename to Sources/SwiftAPIClient/Modifiers/FileIDLine.swift index 03d3641..7abbda8 100644 --- a/Sources/SwiftNetworking/Modifiers/FileIDLine.swift +++ b/Sources/SwiftAPIClient/Modifiers/FileIDLine.swift @@ -1,14 +1,14 @@ import Foundation -public extension NetworkClient { +public extension APIClient { /// Set the fileID and line for logging. When setted `#line` and `#fileID` parameters in the `call` methods are ignored. - func fileIDLine(fileID: String, line: UInt) -> NetworkClient { + func fileIDLine(fileID: String, line: UInt) -> APIClient { configs(\.fileIDLine, FileIDLine(fileID: fileID, line: line)) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The fileID and line of the call site. var fileIDLine: FileIDLine? { diff --git a/Sources/SwiftNetworking/Modifiers/HTTPClientMiddleware.swift b/Sources/SwiftAPIClient/Modifiers/HTTPClientMiddleware.swift similarity index 73% rename from Sources/SwiftNetworking/Modifiers/HTTPClientMiddleware.swift rename to Sources/SwiftAPIClient/Modifiers/HTTPClientMiddleware.swift index 30764f9..10153a2 100644 --- a/Sources/SwiftNetworking/Modifiers/HTTPClientMiddleware.swift +++ b/Sources/SwiftAPIClient/Modifiers/HTTPClientMiddleware.swift @@ -4,29 +4,29 @@ public protocol HTTPClientMiddleware { func execute( request: URLRequest, - configs: NetworkClient.Configs, - next: (URLRequest, NetworkClient.Configs) async throws -> (T, HTTPURLResponse) + configs: APIClient.Configs, + next: (URLRequest, APIClient.Configs) async throws -> (T, HTTPURLResponse) ) async throws -> (T, HTTPURLResponse) } -public extension NetworkClient { +public extension APIClient { /// Add a modifier to the HTTP client. - func httpClientMiddleware(_ middleware: some HTTPClientMiddleware) -> NetworkClient { + func httpClientMiddleware(_ middleware: some HTTPClientMiddleware) -> APIClient { configs { $0.httpClientArrayMiddleware.middlewares.append(middleware) } } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { var httpClientMiddleware: HTTPClientMiddleware { httpClientArrayMiddleware } } -private extension NetworkClient.Configs { +private extension APIClient.Configs { var httpClientArrayMiddleware: HTTPClientArrayMiddleware { get { self[\.httpClientArrayMiddleware] ?? HTTPClientArrayMiddleware() } @@ -40,8 +40,8 @@ private struct HTTPClientArrayMiddleware: HTTPClientMiddleware { func execute( request: URLRequest, - configs: NetworkClient.Configs, - next: (URLRequest, NetworkClient.Configs) async throws -> (T, HTTPURLResponse) + configs: APIClient.Configs, + next: (URLRequest, APIClient.Configs) async throws -> (T, HTTPURLResponse) ) async throws -> (T, HTTPURLResponse) { var next = next for middleware in middlewares { diff --git a/Sources/SwiftNetworking/Modifiers/HTTPResponseValidator.swift b/Sources/SwiftAPIClient/Modifiers/HTTPResponseValidator.swift similarity index 85% rename from Sources/SwiftNetworking/Modifiers/HTTPResponseValidator.swift rename to Sources/SwiftAPIClient/Modifiers/HTTPResponseValidator.swift index 4b194e2..be8989a 100644 --- a/Sources/SwiftNetworking/Modifiers/HTTPResponseValidator.swift +++ b/Sources/SwiftAPIClient/Modifiers/HTTPResponseValidator.swift @@ -8,11 +8,11 @@ public struct HTTPResponseValidator { /// A closure that validates an `HTTPURLResponse` and associated `Data` and the current network client configs. /// - Throws: An error if validation fails. - public var validate: (HTTPURLResponse, Data, NetworkClient.Configs) throws -> Void + public var validate: (HTTPURLResponse, Data, APIClient.Configs) throws -> Void /// Initializes a new `HTTPResponseValidator` with a custom validation closure. /// - Parameter validate: A closure that takes an `HTTPURLResponse` and `Data` and the current network client configs, and throws an error if validation fails. - public init(_ validate: @escaping (HTTPURLResponse, Data, NetworkClient.Configs) throws -> Void) { + public init(_ validate: @escaping (HTTPURLResponse, Data, APIClient.Configs) throws -> Void) { self.validate = validate } } @@ -45,7 +45,7 @@ public extension HTTPResponseValidator { } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The HTTP response validator used for validating network responses. /// Gets the currently set `HTTPResponseValidator`, or `.alwaysSuccess` if not set. @@ -56,12 +56,12 @@ public extension NetworkClient.Configs { } } -public extension NetworkClient { +public extension APIClient { /// Sets a custom HTTP response validator for the network client. /// - Parameter validator: The `HTTPResponseValidator` to be used for validating responses. - /// - Returns: An instance of `NetworkClient` configured with the specified HTTP response validator. - func httpResponseValidator(_ validator: HTTPResponseValidator) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified HTTP response validator. + func httpResponseValidator(_ validator: HTTPResponseValidator) -> APIClient { configs { let oldValidator = $0.httpResponseValidator.validate $0.httpResponseValidator = HTTPResponseValidator { diff --git a/Sources/SwiftNetworking/Modifiers/LoggingModifier.swift b/Sources/SwiftAPIClient/Modifiers/LoggingModifier.swift similarity index 68% rename from Sources/SwiftNetworking/Modifiers/LoggingModifier.swift rename to Sources/SwiftAPIClient/Modifiers/LoggingModifier.swift index e07a3a6..9d97c24 100644 --- a/Sources/SwiftNetworking/Modifiers/LoggingModifier.swift +++ b/Sources/SwiftAPIClient/Modifiers/LoggingModifier.swift @@ -1,29 +1,29 @@ import Foundation import Logging -public extension NetworkClient { +public extension APIClient { /// Sets the custom logger. /// - Parameter logger: The `Logger` to be used for logging messages. - /// - Returns: An instance of `NetworkClient` configured with the specified logging level. - func logger(_ logger: Logger) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified logging level. + func logger(_ logger: Logger) -> APIClient { configs(\.logger, logger) } /// Sets the logging level for the logger. /// - Parameter level: The `Logger.Level` to be used for logging messages. - /// - Returns: An instance of `NetworkClient` configured with the specified logging level. - func log(level: Logger.Level) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified logging level. + func log(level: Logger.Level) -> APIClient { configs(\.logLevel, level) } /// Sets the components to be logged. - func loggingComponents(_ components: LoggingComponents) -> NetworkClient { + func loggingComponents(_ components: LoggingComponents) -> APIClient { configs(\.loggingComponents, components) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The logger used for network operations. /// - Returns: A `Logger` instance configured with the appropriate log level. @@ -47,4 +47,4 @@ public extension NetworkClient.Configs { } } -private let defaultLogger = Logger(label: "swift-networking") +private let defaultLogger = Logger(label: "swift-api-client") diff --git a/Sources/SwiftNetworking/Modifiers/MockResponses.swift b/Sources/SwiftAPIClient/Modifiers/MockResponses.swift similarity index 87% rename from Sources/SwiftNetworking/Modifiers/MockResponses.swift rename to Sources/SwiftAPIClient/Modifiers/MockResponses.swift index c51ad76..e17eaa8 100644 --- a/Sources/SwiftNetworking/Modifiers/MockResponses.swift +++ b/Sources/SwiftAPIClient/Modifiers/MockResponses.swift @@ -3,7 +3,7 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { /// Use this method to specify a mock response for a specific request. /// The usage of the mock is configured by the `usingMocks(policy:)` modifier. @@ -11,9 +11,9 @@ public extension NetworkClient { /// You can set a value of either the response type or `Data`. /// /// - Parameter value: The mock value to be returned for requests expecting a response of type `T`. - /// - Returns: An instance of `NetworkClient` configured with the specified mock. + /// - Returns: An instance of `APIClient` configured with the specified mock. /// - func mock(_ value: T) -> NetworkClient { + func mock(_ value: T) -> APIClient { configs { $0.mocks[ObjectIdentifier(T.self)] = value } @@ -21,13 +21,13 @@ public extension NetworkClient { /// Configures the client to use a specific policy for handling mocks. /// - Parameter policy: The `UsingMockPolicy` indicating how mocks should be used. - /// - Returns: An instance of `NetworkClient` configured with the specified mock policy. - func usingMocks(policy: UsingMocksPolicy) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified mock policy. + func usingMocks(policy: UsingMocksPolicy) -> APIClient { configs(\.usingMocksPolicy, policy) } } -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The policy for using mock responses in the client. var usingMocksPolicy: UsingMocksPolicy { @@ -45,7 +45,7 @@ public extension NetworkClient.Configs { /// Returns a new configuration set with a specified mock response. /// - Parameters: /// - mock: The mock response to add to the configuration. - /// - Returns: A new `NetworkClient.Configs` instance with the specified mock. + /// - Returns: A new `APIClient.Configs` instance with the specified mock. func with(mock: T) -> Self { var new = self new.mocks[ObjectIdentifier(T.self)] = mock @@ -99,7 +99,7 @@ public enum UsingMocksPolicy: Hashable { case require } -private extension NetworkClient.Configs { +private extension APIClient.Configs { var mocks: [ObjectIdentifier: Any] { get { self[\.mocks] ?? [:] } diff --git a/Sources/SwiftNetworking/Modifiers/RedirectModifier.swift b/Sources/SwiftAPIClient/Modifiers/RedirectModifier.swift similarity index 87% rename from Sources/SwiftNetworking/Modifiers/RedirectModifier.swift rename to Sources/SwiftAPIClient/Modifiers/RedirectModifier.swift index 8265d84..ade5e79 100644 --- a/Sources/SwiftNetworking/Modifiers/RedirectModifier.swift +++ b/Sources/SwiftAPIClient/Modifiers/RedirectModifier.swift @@ -1,7 +1,7 @@ import Foundation #if !canImport(FoundationNetworking) -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// The redirect behaviour for the client. Default is `.follow`. var redirectBehaviour: RedirectBehaviour { @@ -10,7 +10,7 @@ public extension NetworkClient.Configs { } } -public extension NetworkClient { +public extension APIClient { /// Sets the redirect behaviour for the client. Default is `.follow`. /// - Note: Redirect behaviour is only applicable to clients that use `URLSession`. diff --git a/Sources/SwiftNetworking/Modifiers/RequestCompression.swift b/Sources/SwiftAPIClient/Modifiers/RequestCompression.swift similarity index 98% rename from Sources/SwiftNetworking/Modifiers/RequestCompression.swift rename to Sources/SwiftAPIClient/Modifiers/RequestCompression.swift index 013a8db..5575cca 100644 --- a/Sources/SwiftNetworking/Modifiers/RequestCompression.swift +++ b/Sources/SwiftAPIClient/Modifiers/RequestCompression.swift @@ -5,7 +5,7 @@ import zlib import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { /// Compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the /// appropriate header. @@ -23,7 +23,7 @@ public extension NetworkClient { func compressRequest( duplicateHeaderBehavior: DuplicateHeaderBehavior = .skip, shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true } - ) -> NetworkClient { + ) -> APIClient { beforeCall { urlRequest, _ in // No need to compress unless we have body data. No support for compressing streams. guard let bodyData = urlRequest.httpBody else { diff --git a/Sources/SwiftNetworking/Modifiers/RequestModifiers.swift b/Sources/SwiftAPIClient/Modifiers/RequestModifiers.swift similarity index 70% rename from Sources/SwiftNetworking/Modifiers/RequestModifiers.swift rename to Sources/SwiftAPIClient/Modifiers/RequestModifiers.swift index c62d805..989cda7 100644 --- a/Sources/SwiftNetworking/Modifiers/RequestModifiers.swift +++ b/Sources/SwiftAPIClient/Modifiers/RequestModifiers.swift @@ -5,26 +5,26 @@ import FoundationNetworking // MARK: - Path modifiers -public extension NetworkClient { +public extension APIClient { /// Appends path components to the URL of the request. /// - Parameter path: A variadic list of components that conform to `CustomStringConvertible`. - /// - Returns: An instance of `NetworkClient` with updated path. - func callAsFunction(_ path: CustomStringConvertible, _ suffix: any CustomStringConvertible...) -> NetworkClient { + /// - Returns: An instance of `APIClient` with updated path. + func callAsFunction(_ path: CustomStringConvertible, _ suffix: any CustomStringConvertible...) -> APIClient { self.path([path] + suffix) } /// Appends path components to the URL of the request. /// - Parameter components: A variadic list of components that conform to `CustomStringConvertible`. - /// - Returns: An instance of `NetworkClient` with updated path. - func path(_ components: any CustomStringConvertible...) -> NetworkClient { + /// - Returns: An instance of `APIClient` with updated path. + func path(_ components: any CustomStringConvertible...) -> APIClient { path(components) } /// Appends an array of path components to the URL of the request. /// - Parameter components: An array of components that conform to `CustomStringConvertible`. - /// - Returns: An instance of `NetworkClient` with updated path. - func path(_ components: [any CustomStringConvertible]) -> NetworkClient { + /// - Returns: An instance of `APIClient` with updated path. + func path(_ components: [any CustomStringConvertible]) -> APIClient { modifyRequest { for component in components { $0.url?.appendPathComponent(component.description) @@ -35,39 +35,39 @@ public extension NetworkClient { // MARK: - Method modifiers -public extension NetworkClient { +public extension APIClient { /// Sets the HTTP method for the request. /// - Parameter method: The `HTTPMethod` to set for the request. - /// - Returns: An instance of `NetworkClient` with the specified HTTP method. - func method(_ method: HTTPMethod) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified HTTP method. + func method(_ method: HTTPMethod) -> APIClient { modifyRequest { $0.method = method } } /// Sets the HTTP `GET` method for the request. - var get: NetworkClient { method(.get) } + var get: APIClient { method(.get) } /// Sets the HTTP `POST` method for the request. - var post: NetworkClient { method(.post) } + var post: APIClient { method(.post) } /// Sets the HTTP `PUT` method for the request. - var put: NetworkClient { method(.put) } + var put: APIClient { method(.put) } /// Sets the HTTP `DELETE` method for the request. - var delete: NetworkClient { method(.delete) } + var delete: APIClient { method(.delete) } /// Sets the HTTP `PATCH` method for the request. - var patch: NetworkClient { method(.patch) } + var patch: APIClient { method(.patch) } } // MARK: - Headers modifiers -public extension NetworkClient { +public extension APIClient { /// Adds or updates HTTP headers for the request. /// - Parameters: /// - headers: A variadic list of `HTTPHeader` to set or update. /// - update: A Boolean to determine whether to update existing headers. Default is `false`. - /// - Returns: An instance of `NetworkClient` with modified headers. - func headers(_ headers: HTTPHeader..., update: Bool = false) -> NetworkClient { + /// - Returns: An instance of `APIClient` with modified headers. + func headers(_ headers: HTTPHeader..., update: Bool = false) -> APIClient { modifyRequest { for header in headers { if update { @@ -81,8 +81,8 @@ public extension NetworkClient { /// Removes a specific HTTP header from the request. /// - Parameter field: The key of the header to remove. - /// - Returns: An instance of `NetworkClient` with the specified header removed. - func removeHeader(_ field: HTTPHeader.Key) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified header removed. + func removeHeader(_ field: HTTPHeader.Key) -> APIClient { modifyRequest { $0.setValue(nil, forHTTPHeaderField: field.rawValue) } @@ -93,22 +93,22 @@ public extension NetworkClient { /// - field: The key of the header to add or update. /// - value: The value for the header. /// - update: A Boolean to determine whether to update the header if it exists. Default is `false`. - /// - Returns: An instance of `NetworkClient` with modified header. - func header(_ field: HTTPHeader.Key, _ value: String, update: Bool = false) -> NetworkClient { + /// - Returns: An instance of `APIClient` with modified header. + func header(_ field: HTTPHeader.Key, _ value: String, update: Bool = false) -> APIClient { headers(HTTPHeader(field, value), update: update) } } // MARK: - Body modifiers -public extension NetworkClient { +public extension APIClient { /// Sets the request body with a specified value and serializer. /// - Parameters: /// - value: The value to be serialized and set as the body. /// - serializer: The `ContentSerializer` used to serialize the body value. - /// - Returns: An instance of `NetworkClient` with the serialized body. - func body(_ value: T, as serializer: ContentSerializer) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the serialized body. + func body(_ value: T, as serializer: ContentSerializer) -> APIClient { modifyRequest { req, configs in let (data, contentType) = try serializer.serialize(value, configs) req.httpBodyStream = nil @@ -121,30 +121,30 @@ public extension NetworkClient { /// Sets the request body with an `Encodable` value. /// - Parameter value: The `Encodable` value to set as the body. - /// - Returns: An instance of `NetworkClient` with the serialized body. - func body(_ value: any Encodable) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the serialized body. + func body(_ value: any Encodable) -> APIClient { body(AnyEncodable(value), as: .encodable) } /// Sets the request body with an `Encodable` value. /// - Parameter dictionary: The dictionary of encodable values to set as the body. - /// - Returns: An instance of `NetworkClient` with the serialized body. + /// - Returns: An instance of `APIClient` with the serialized body. @_disfavoredOverload - func body(_ dictionary: [String: Encodable?]) -> NetworkClient { + func body(_ dictionary: [String: Encodable?]) -> APIClient { body(dictionary.compactMapValues { $0.map { AnyEncodable($0) } }, as: .encodable) } /// Sets the request body with a closure that provides `Data`. /// - Parameter data: A closure returning the `Data` to be set as the body. - /// - Returns: An instance of `NetworkClient` with the specified body. - func body(_ data: @escaping @autoclosure () throws -> Data) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified body. + func body(_ data: @escaping @autoclosure () throws -> Data) -> APIClient { body { _ in try data() } } /// Sets the request body with a closure that dynamically provides `Data` based on configurations. /// - Parameter data: A closure taking `Configs` and returning `Data` to be set as the body. - /// - Returns: An instance of `NetworkClient` with the specified body. - func body(_ data: @escaping (Configs) throws -> Data) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified body. + func body(_ data: @escaping (Configs) throws -> Data) -> APIClient { modifyRequest { req, configs in req.httpBodyStream = nil req.httpBody = try data(configs) @@ -152,14 +152,14 @@ public extension NetworkClient { } } -public extension NetworkClient { +public extension APIClient { /// Sets the request body stream with a specified value and serializer. /// - Parameters: /// - value: The value to be serialized and set as the body stream. /// - serializer: The `ContentSerializer` used to serialize the body stream value. - /// - Returns: An instance of `NetworkClient` with the serialized body stream. - func bodyStream(_ value: T, as serializer: ContentSerializer) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the serialized body stream. + func bodyStream(_ value: T, as serializer: ContentSerializer) -> APIClient { modifyRequest { req, configs in let (data, contentType) = try serializer.serialize(value, configs) req.httpBodyStream = InputStream(data: data) @@ -172,23 +172,23 @@ public extension NetworkClient { /// Sets the request body stream with an `Encodable` value. /// - Parameter value: The `Encodable` value to set as the body stream. - /// - Returns: An instance of `NetworkClient` with the serialized body stream. - func bodyStream(_ value: any Encodable) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the serialized body stream. + func bodyStream(_ value: any Encodable) -> APIClient { bodyStream(AnyEncodable(value), as: .encodable) } /// Sets the request body stream with an `Encodable` value. /// - Parameter dictionary: The dictionary of encodable values to set as the body stream. - /// - Returns: An instance of `NetworkClient` with the serialized body stream. + /// - Returns: An instance of `APIClient` with the serialized body stream. @_disfavoredOverload - func bodyStream(_ dictionary: [String: Encodable?]) -> NetworkClient { + func bodyStream(_ dictionary: [String: Encodable?]) -> APIClient { bodyStream(dictionary.compactMapValues { $0.map { AnyEncodable($0) } }, as: .encodable) } /// Sets the request body stream with a file URL. /// - Parameter file: The file URL to set as the body stream. - /// - Returns: An instance of `NetworkClient` with the specified body stream. - func bodyStream(file url: URL) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified body stream. + func bodyStream(file url: URL) -> APIClient { bodyStream { _ in guard let stream = InputStream(url: url) else { throw Errors.invalidFileURL(url) @@ -199,15 +199,15 @@ public extension NetworkClient { /// Sets the request body stream with a closure that provides `InputStream`. /// - Parameter stream: A closure returning the `InputStream` to be set as the body stream. - /// - Returns: An instance of `NetworkClient` with the specified body stream. - func bodyStream(_ stream: @escaping @autoclosure () throws -> InputStream) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified body stream. + func bodyStream(_ stream: @escaping @autoclosure () throws -> InputStream) -> APIClient { bodyStream { _ in try stream() } } /// Sets the request body stream with a closure that dynamically provides `InputStream` based on configurations. /// - Parameter stream: A closure taking `Configs` and returning `InputStream` to be set as the body stream. - /// - Returns: An instance of `NetworkClient` with the specified body stream. - func bodyStream(_ stream: @escaping (Configs) throws -> InputStream) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified body stream. + func bodyStream(_ stream: @escaping (Configs) throws -> InputStream) -> APIClient { modifyRequest { req, configs in req.httpBody = nil req.httpBodyStream = try stream(configs) @@ -217,12 +217,12 @@ public extension NetworkClient { // MARK: - Query modifiers -public extension NetworkClient { +public extension APIClient { /// Adds URL query parameters using a closure providing an array of `URLQueryItem`. /// - Parameter items: A closure returning an array of `URLQueryItem` to be set as query parameters. - /// - Returns: An instance of `NetworkClient` with set query parameters. - func query(_ items: @escaping @autoclosure () throws -> [URLQueryItem]) -> NetworkClient { + /// - Returns: An instance of `APIClient` with set query parameters. + func query(_ items: @escaping @autoclosure () throws -> [URLQueryItem]) -> APIClient { query { _ in try items() } @@ -230,8 +230,8 @@ public extension NetworkClient { /// Adds URL query parameters with a closure that dynamically provides an array of `URLQueryItem` based on configurations. /// - Parameter items: A closure taking `Configs` and returning an array of `URLQueryItem`. - /// - Returns: An instance of `NetworkClient` with set query parameters. - func query(_ items: @escaping (Configs) throws -> [URLQueryItem]) -> NetworkClient { + /// - Returns: An instance of `APIClient` with set query parameters. + func query(_ items: @escaping (Configs) throws -> [URLQueryItem]) -> APIClient { modifyRequest { req, configs in if let url = req.url, @@ -259,8 +259,8 @@ public extension NetworkClient { /// - Parameters: /// - field: The field name of the query parameter. /// - value: The value of the query parameter. - /// - Returns: An instance of `NetworkClient` with the specified query parameter. - func query(_ field: String, _ value: String?) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified query parameter. + func query(_ field: String, _ value: String?) -> APIClient { query(value.map { [URLQueryItem(name: field, value: $0)] } ?? []) } @@ -268,15 +268,15 @@ public extension NetworkClient { /// - Parameters: /// - field: The field name of the query parameter. /// - value: The value of the query parameter, conforming to `RawRepresentable`. - /// - Returns: An instance of `NetworkClient` with the specified query parameter. - func query(_ field: String, _ value: R?) -> NetworkClient where R.RawValue == String { + /// - Returns: An instance of `APIClient` with the specified query parameter. + func query(_ field: String, _ value: R?) -> APIClient where R.RawValue == String { query(field, value?.rawValue) } /// Adds URL query parameters using an `Encodable` object. /// - Parameter items: An `Encodable` object to be used as query parameters. - /// - Returns: An instance of `NetworkClient` with set query parameters. - func query(_ items: any Encodable) -> NetworkClient { + /// - Returns: An instance of `APIClient` with set query parameters. + func query(_ items: any Encodable) -> APIClient { query { try $0.queryEncoder.encode(items) } @@ -284,8 +284,8 @@ public extension NetworkClient { /// Adds URL query parameters using a dictionary of JSON objects. /// - Parameter json: A dictionary of `String: JSON` pairs to be used as query parameters. - /// - Returns: An instance of `NetworkClient` with set query parameters. - func query(_ parameters: [String: Encodable?]) -> NetworkClient { + /// - Returns: An instance of `APIClient` with set query parameters. + func query(_ parameters: [String: Encodable?]) -> APIClient { query { try $0.queryEncoder .encode(parameters.compactMapValues { $0.map { AnyEncodable($0) }}) @@ -297,25 +297,25 @@ public extension NetworkClient { /// - Parameters: /// - field: The field name of the query parameter. /// - value: The value of the query parameter, conforming to `Encodable`. - /// - Returns: An instance of `NetworkClient` with the specified query parameter. + /// - Returns: An instance of `APIClient` with the specified query parameter. @_disfavoredOverload - func query(_ field: String, _ value: Encodable?) -> NetworkClient { + func query(_ field: String, _ value: Encodable?) -> APIClient { query([field: value]) } } // MARK: - URL modifiers -public extension NetworkClient { +public extension APIClient { /// Sets the base URL for the request. /// /// - Parameters: /// - newBaseURL: The new base URL to set. - /// - Returns: An instance of `NetworkClient` with the updated base URL. + /// - Returns: An instance of `APIClient` with the updated base URL. /// /// - Note: The path, query, and fragment of the original URL are retained, while those of the new URL are ignored. - func baseURL(_ newBaseURL: URL) -> NetworkClient { + func baseURL(_ newBaseURL: URL) -> APIClient { modifyURLComponents { components in components.scheme = newBaseURL.scheme components.host = newBaseURL.host @@ -326,8 +326,8 @@ public extension NetworkClient { /// Sets the scheme for the request. /// /// - Parameter scheme: The new scheme to set. - /// - Returns: An instance of `NetworkClient` with the updated scheme. - func scheme(_ scheme: String) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the updated scheme. + func scheme(_ scheme: String) -> APIClient { modifyURLComponents { components in components.scheme = scheme } @@ -336,8 +336,8 @@ public extension NetworkClient { /// Sets the host for the request. /// /// - Parameter host: The new host to set. - /// - Returns: An instance of `NetworkClient` with the updated host. - func host(_ host: String) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the updated host. + func host(_ host: String) -> APIClient { modifyURLComponents { components in components.host = host } @@ -346,21 +346,21 @@ public extension NetworkClient { /// Sets the port for the request. /// /// - Parameter port: The new port to set. - /// - Returns: An instance of `NetworkClient` with the updated port. - func port(_ port: Int?) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the updated port. + func port(_ port: Int?) -> APIClient { modifyURLComponents { components in components.port = port } } } -public extension NetworkClient { +public extension APIClient { /// Modifies the URL the request via URLComponents. /// /// - Parameter modifier: A closure that takes the current URL components and modifies them. - /// - Returns: An instance of `NetworkClient` with the modified URL components. - func modifyURLComponents(_ modifier: @escaping (inout URLComponents) throws -> Void) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the modified URL components. + func modifyURLComponents(_ modifier: @escaping (inout URLComponents) throws -> Void) -> APIClient { modifyRequest { req, configs in guard let url = req.url else { configs.logger.error("Failed to get URL of request") @@ -386,12 +386,12 @@ public extension NetworkClient { // MARK: - Timeout modifiers -public extension NetworkClient { +public extension APIClient { /// Sets the URLRequest timeoutInterval property. /// - Parameter timeout: The timeout interval to set for the request. - /// - Returns: An instance of `NetworkClient` with the specified timeout interval. - func timeoutInterval(_ timeout: TimeInterval) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified timeout interval. + func timeoutInterval(_ timeout: TimeInterval) -> APIClient { modifyRequest { $0.timeoutInterval = timeout } @@ -400,12 +400,12 @@ public extension NetworkClient { // MARK: - Cache policy modifiers -public extension NetworkClient { +public extension APIClient { /// Sets the URLRequest cachePolicy property. /// - Parameter policy: The cache policy to set for the request. - /// - Returns: An instance of `NetworkClient` with the specified cache policy. - func cachePolicy(_ policy: URLRequest.CachePolicy) -> NetworkClient { + /// - Returns: An instance of `APIClient` with the specified cache policy. + func cachePolicy(_ policy: URLRequest.CachePolicy) -> APIClient { modifyRequest { $0.cachePolicy = policy } diff --git a/Sources/SwiftNetworking/Modifiers/RequestValidator.swift b/Sources/SwiftAPIClient/Modifiers/RequestValidator.swift similarity index 70% rename from Sources/SwiftNetworking/Modifiers/RequestValidator.swift rename to Sources/SwiftAPIClient/Modifiers/RequestValidator.swift index ce04967..7d25bfe 100644 --- a/Sources/SwiftNetworking/Modifiers/RequestValidator.swift +++ b/Sources/SwiftAPIClient/Modifiers/RequestValidator.swift @@ -8,11 +8,11 @@ public struct RequestValidator { /// A closure that validates a `URLRequest`. /// - Throws: An error if validation fails. - public var validate: (_ request: URLRequest, NetworkClient.Configs) throws -> Void + public var validate: (_ request: URLRequest, APIClient.Configs) throws -> Void /// Initializes a new `RequestValidator` with a custom validation closure. /// - Parameter validate: A closure that takes a `URLRequest` and throws an error if validation fails. - public init(validate: @escaping (_ request: URLRequest, NetworkClient.Configs) throws -> Void) { + public init(validate: @escaping (_ request: URLRequest, APIClient.Configs) throws -> Void) { self.validate = validate } } @@ -25,12 +25,12 @@ public extension RequestValidator { } } -public extension NetworkClient { +public extension APIClient { /// Sets a custom request validator for the network client. /// - Parameter validator: The `RequestValidator` to be used for validating `URLRequest` instances. - /// - Returns: An instance of `NetworkClient` configured with the specified request validator. - func requestValidator(_ validator: RequestValidator) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified request validator. + func requestValidator(_ validator: RequestValidator) -> APIClient { beforeCall { try validator.validate($0, $1) } diff --git a/Sources/SwiftNetworking/Modifiers/ResponseWrapModifires.swift b/Sources/SwiftAPIClient/Modifiers/ResponseWrapModifires.swift similarity index 74% rename from Sources/SwiftNetworking/Modifiers/ResponseWrapModifires.swift rename to Sources/SwiftAPIClient/Modifiers/ResponseWrapModifires.swift index 89aa3d1..91b39f7 100644 --- a/Sources/SwiftNetworking/Modifiers/ResponseWrapModifires.swift +++ b/Sources/SwiftAPIClient/Modifiers/ResponseWrapModifires.swift @@ -3,12 +3,12 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { /// Configures the network client to use a custom decoder as specified by the provided mapping function. /// - Parameter mapper: A closure that takes an existing `DataDecoder` and returns a modified `DataDecoder`. - /// - Returns: An instance of `NetworkClient` configured with the specified decoder. - func mapDecoder(_ mapper: @escaping (any DataDecoder) -> any DataDecoder) -> NetworkClient { + /// - Returns: An instance of `APIClient` configured with the specified decoder. + func mapDecoder(_ mapper: @escaping (any DataDecoder) -> any DataDecoder) -> APIClient { configs { $0.bodyDecoder = mapper($0.bodyDecoder) } diff --git a/Sources/SwiftNetworking/Modifiers/RetryModifier.swift b/Sources/SwiftAPIClient/Modifiers/RetryModifier.swift similarity index 81% rename from Sources/SwiftNetworking/Modifiers/RetryModifier.swift rename to Sources/SwiftAPIClient/Modifiers/RetryModifier.swift index e1791a1..5ecd9d1 100644 --- a/Sources/SwiftNetworking/Modifiers/RetryModifier.swift +++ b/Sources/SwiftAPIClient/Modifiers/RetryModifier.swift @@ -3,10 +3,10 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient { +public extension APIClient { /// Retries the request if it fails. - func retry(limit: Int?) -> NetworkClient { + func retry(limit: Int?) -> APIClient { httpClientMiddleware(RetryMiddleware(limit: limit)) } } @@ -17,8 +17,8 @@ private struct RetryMiddleware: HTTPClientMiddleware { func execute( request: URLRequest, - configs: NetworkClient.Configs, - next: (URLRequest, NetworkClient.Configs) async throws -> (T, HTTPURLResponse) + configs: APIClient.Configs, + next: (URLRequest, APIClient.Configs) async throws -> (T, HTTPURLResponse) ) async throws -> (T, HTTPURLResponse) { var count = 0 func needRetry() -> Bool { diff --git a/Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenCacheService.swift b/Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenCacheService.swift similarity index 98% rename from Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenCacheService.swift rename to Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenCacheService.swift index aaadd68..190f4e4 100644 --- a/Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenCacheService.swift +++ b/Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenCacheService.swift @@ -65,7 +65,7 @@ public struct KeychainTokenCacheService: TokenCacheService { public let service: String public init( - account: String = "networkclient.token", + account: String = "apiclient.token", service: String = "TokenCacheService" ) { self.account = account diff --git a/Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenRefresher.swift b/Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenRefresher.swift similarity index 80% rename from Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenRefresher.swift rename to Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenRefresher.swift index 0094228..bc498eb 100644 --- a/Sources/SwiftNetworking/Modifiers/TokenRefresher/TokenRefresher.swift +++ b/Sources/SwiftAPIClient/Modifiers/TokenRefresher/TokenRefresher.swift @@ -5,7 +5,7 @@ public extension HTTPClientMiddleware where Self == TokenRefresherMiddleware { static func tokenRefresher( cacheService: TokenCacheService = valueFor(live: .keychain, test: .mock), expiredStatusCodes: Set = [.unauthorized], - refreshToken: @escaping (NetworkClient.Configs) async throws -> String, + refreshToken: @escaping (APIClient.Configs) async throws -> String, auth: @escaping (String) -> AuthModifier ) -> Self { TokenRefresherMiddleware( @@ -17,12 +17,12 @@ public extension HTTPClientMiddleware where Self == TokenRefresherMiddleware { } } -extension NetworkClient { +extension APIClient { public func tokenRefresher( cacheService: TokenCacheService = valueFor(live: .keychain, test: .mock), expiredStatusCodes: Set = [.unauthorized], - refreshToken: @escaping (NetworkClient, NetworkClient.Configs) async throws -> String, + refreshToken: @escaping (APIClient, APIClient.Configs) async throws -> String, auth: @escaping (String) -> AuthModifier ) -> Self { httpClientMiddleware( @@ -41,12 +41,12 @@ public struct TokenRefresherMiddleware: HTTPClientMiddleware { private let tokenCacheService: TokenCacheService private let expiredStatusCodes: Set private let auth: (String) -> AuthModifier - private let refreshToken: (NetworkClient.Configs) async throws -> String + private let refreshToken: (APIClient.Configs) async throws -> String public init( cacheService: TokenCacheService, expiredStatusCodes: Set = [.unauthorized], - refreshToken: @escaping (NetworkClient.Configs) async throws -> String, + refreshToken: @escaping (APIClient.Configs) async throws -> String, auth: @escaping (String) -> AuthModifier ) { tokenCacheService = cacheService @@ -57,8 +57,8 @@ public struct TokenRefresherMiddleware: HTTPClientMiddleware { public func execute( request: URLRequest, - configs: NetworkClient.Configs, - next: (URLRequest, NetworkClient.Configs) async throws -> (T, HTTPURLResponse) + configs: APIClient.Configs, + next: (URLRequest, APIClient.Configs) async throws -> (T, HTTPURLResponse) ) async throws -> (T, HTTPURLResponse) { var token: String let currentToken = tokenCacheService.getToken() @@ -79,7 +79,7 @@ public struct TokenRefresherMiddleware: HTTPClientMiddleware { return result } - private func refreshTokenAndCache(_ configs: NetworkClient.Configs) async throws -> String { + private func refreshTokenAndCache(_ configs: APIClient.Configs) async throws -> String { let token = try await refreshToken(configs) try? tokenCacheService.saveToken(token) return token diff --git a/Sources/SwiftNetworking/Modifiers/URLSessionModifiers.swift b/Sources/SwiftAPIClient/Modifiers/URLSessionModifiers.swift similarity index 86% rename from Sources/SwiftNetworking/Modifiers/URLSessionModifiers.swift rename to Sources/SwiftAPIClient/Modifiers/URLSessionModifiers.swift index 26c2046..c4d848b 100644 --- a/Sources/SwiftNetworking/Modifiers/URLSessionModifiers.swift +++ b/Sources/SwiftAPIClient/Modifiers/URLSessionModifiers.swift @@ -3,11 +3,11 @@ import Foundation import FoundationNetworking #endif -public extension NetworkClient.Configs { +public extension APIClient.Configs { /// Underlying URLSession of the client. var urlSession: URLSession { - let session = URLSession.networkClient + let session = URLSession.apiClient #if !canImport(FoundationNetworking) SessionDelegateProxy.shared.configs = self #endif @@ -24,7 +24,7 @@ public extension NetworkClient.Configs { } #if !canImport(FoundationNetworking) -public extension NetworkClient { +public extension APIClient { /// Sets the URLSession delegate for the client. func urlSession(delegate: URLSessionDelegate?) -> Self { @@ -35,7 +35,7 @@ public extension NetworkClient { private extension URLSession { - static var networkClient: URLSession = { + static var apiClient: URLSession = { #if !canImport(FoundationNetworking) var configs = URLSessionConfiguration.default configs.headers = .default diff --git a/Sources/SwiftNetworking/Types/AsyncValue.swift b/Sources/SwiftAPIClient/Types/AsyncValue.swift similarity index 100% rename from Sources/SwiftNetworking/Types/AsyncValue.swift rename to Sources/SwiftAPIClient/Types/AsyncValue.swift diff --git a/Sources/SwiftNetworking/Types/ContentSerializer.swift b/Sources/SwiftAPIClient/Types/ContentSerializer.swift similarity index 85% rename from Sources/SwiftNetworking/Types/ContentSerializer.swift rename to Sources/SwiftAPIClient/Types/ContentSerializer.swift index b49b71a..16e2711 100644 --- a/Sources/SwiftNetworking/Types/ContentSerializer.swift +++ b/Sources/SwiftAPIClient/Types/ContentSerializer.swift @@ -4,12 +4,12 @@ import Foundation public struct ContentSerializer { /// A closure that serializes a value of type `T` into `Data` and a corresponding `ContentType`. - public var serialize: (_ value: T, _ configs: NetworkClient.Configs) throws -> (Data, ContentType) + public var serialize: (_ value: T, _ configs: APIClient.Configs) throws -> (Data, ContentType) /// Initializes a new `ContentSerializer` with a custom serialization closure. /// - Parameter serialize: A closure that takes a value and network configurations and returns serialized data and its content type. public init( - _ serialize: @escaping (T, NetworkClient.Configs) throws -> (Data, ContentType) + _ serialize: @escaping (T, APIClient.Configs) throws -> (Data, ContentType) ) { self.serialize = serialize } diff --git a/Sources/SwiftNetworking/Types/ContentType.swift b/Sources/SwiftAPIClient/Types/ContentType.swift similarity index 100% rename from Sources/SwiftNetworking/Types/ContentType.swift rename to Sources/SwiftAPIClient/Types/ContentType.swift diff --git a/Sources/SwiftNetworking/Types/Errors.swift b/Sources/SwiftAPIClient/Types/Errors.swift similarity index 100% rename from Sources/SwiftNetworking/Types/Errors.swift rename to Sources/SwiftAPIClient/Types/Errors.swift diff --git a/Sources/SwiftNetworking/Types/HTTPHeaderKey.swift b/Sources/SwiftAPIClient/Types/HTTPHeaderKey.swift similarity index 100% rename from Sources/SwiftNetworking/Types/HTTPHeaderKey.swift rename to Sources/SwiftAPIClient/Types/HTTPHeaderKey.swift diff --git a/Sources/SwiftNetworking/Types/HTTPHeaders.swift b/Sources/SwiftAPIClient/Types/HTTPHeaders.swift similarity index 100% rename from Sources/SwiftNetworking/Types/HTTPHeaders.swift rename to Sources/SwiftAPIClient/Types/HTTPHeaders.swift diff --git a/Sources/SwiftNetworking/Types/HTTPMethod.swift b/Sources/SwiftAPIClient/Types/HTTPMethod.swift similarity index 100% rename from Sources/SwiftNetworking/Types/HTTPMethod.swift rename to Sources/SwiftAPIClient/Types/HTTPMethod.swift diff --git a/Sources/SwiftNetworking/Types/HTTPStatusCode.swift b/Sources/SwiftAPIClient/Types/HTTPStatusCode.swift similarity index 100% rename from Sources/SwiftNetworking/Types/HTTPStatusCode.swift rename to Sources/SwiftAPIClient/Types/HTTPStatusCode.swift diff --git a/Sources/SwiftNetworking/Types/LoggingComponent.swift b/Sources/SwiftAPIClient/Types/LoggingComponent.swift similarity index 100% rename from Sources/SwiftNetworking/Types/LoggingComponent.swift rename to Sources/SwiftAPIClient/Types/LoggingComponent.swift diff --git a/Sources/SwiftNetworking/Types/Mockable.swift b/Sources/SwiftAPIClient/Types/Mockable.swift similarity index 100% rename from Sources/SwiftNetworking/Types/Mockable.swift rename to Sources/SwiftAPIClient/Types/Mockable.swift diff --git a/Sources/SwiftNetworking/Types/RedirectBehaviour.swift b/Sources/SwiftAPIClient/Types/RedirectBehaviour.swift similarity index 100% rename from Sources/SwiftNetworking/Types/RedirectBehaviour.swift rename to Sources/SwiftAPIClient/Types/RedirectBehaviour.swift diff --git a/Sources/SwiftNetworking/Types/Serializer.swift b/Sources/SwiftAPIClient/Types/Serializer.swift similarity index 89% rename from Sources/SwiftNetworking/Types/Serializer.swift rename to Sources/SwiftAPIClient/Types/Serializer.swift index ad4bdfe..3ce75ca 100644 --- a/Sources/SwiftNetworking/Types/Serializer.swift +++ b/Sources/SwiftAPIClient/Types/Serializer.swift @@ -4,11 +4,11 @@ import Foundation public struct Serializer { /// A closure that serializes a network response into a specified type. - public var serialize: (_ response: Response, _ configs: NetworkClient.Configs) throws -> T + public var serialize: (_ response: Response, _ configs: APIClient.Configs) throws -> T /// Initializes a new `Serializer` with a custom serialization closure. /// - Parameter serialize: A closure that takes a response and network configurations, then returns a serialized object of type `T`. - public init(_ serialize: @escaping (Response, NetworkClient.Configs) throws -> T) { + public init(_ serialize: @escaping (Response, APIClient.Configs) throws -> T) { self.serialize = serialize } } diff --git a/Sources/SwiftNetworking/Utils/AnyAsyncSequence.swift b/Sources/SwiftAPIClient/Utils/AnyAsyncSequence.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/AnyAsyncSequence.swift rename to Sources/SwiftAPIClient/Utils/AnyAsyncSequence.swift diff --git a/Sources/SwiftNetworking/Utils/AnyEncodable.swift b/Sources/SwiftAPIClient/Utils/AnyEncodable.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/AnyEncodable.swift rename to Sources/SwiftAPIClient/Utils/AnyEncodable.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/ContentEncoder.swift b/Sources/SwiftAPIClient/Utils/Coders/ContentEncoder.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/ContentEncoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/ContentEncoder.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/DataDecoder.swift b/Sources/SwiftAPIClient/Utils/Coders/DataDecoder.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/DataDecoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/DataDecoder.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/ErrorDecoder.swift b/Sources/SwiftAPIClient/Utils/Coders/ErrorDecoder.swift similarity index 77% rename from Sources/SwiftNetworking/Utils/Coders/ErrorDecoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/ErrorDecoder.swift index 0c06f14..26306a6 100644 --- a/Sources/SwiftNetworking/Utils/Coders/ErrorDecoder.swift +++ b/Sources/SwiftAPIClient/Utils/Coders/ErrorDecoder.swift @@ -3,9 +3,9 @@ import Foundation /// A type that represents an error decoding from a response body. public struct ErrorDecoder { - public var decodeError: (Data, NetworkClient.Configs) -> Error? + public var decodeError: (Data, APIClient.Configs) -> Error? - public init(decodeError: @escaping (Data, NetworkClient.Configs) -> Error?) { + public init(decodeError: @escaping (Data, APIClient.Configs) -> Error?) { self.decodeError = decodeError } } @@ -21,7 +21,7 @@ public extension ErrorDecoder { /// /// - Parameters: /// - type: The type of the decodable error. - /// - dataDecoder: The `DataDecoder` to use for decoding. If `nil`, the `bodyDecoder` of the `NetworkClient.Configs` will be used. + /// - dataDecoder: The `DataDecoder` to use for decoding. If `nil`, the `bodyDecoder` of the `APIClient.Configs` will be used. static func decodable( _ type: Failure.Type, dataDecoder: (any DataDecoder)? = nil diff --git a/Sources/SwiftNetworking/Utils/Coders/FormURLEncoder.swift b/Sources/SwiftAPIClient/Utils/Coders/FormURLEncoder.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/FormURLEncoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/FormURLEncoder.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/JSONContentEncoders.swift b/Sources/SwiftAPIClient/Utils/Coders/JSONContentEncoders.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/JSONContentEncoders.swift rename to Sources/SwiftAPIClient/Utils/Coders/JSONContentEncoders.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/MultipartFormData/MultipartFormData.swift b/Sources/SwiftAPIClient/Utils/Coders/MultipartFormData/MultipartFormData.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/MultipartFormData/MultipartFormData.swift rename to Sources/SwiftAPIClient/Utils/Coders/MultipartFormData/MultipartFormData.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift b/Sources/SwiftAPIClient/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift similarity index 98% rename from Sources/SwiftNetworking/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift index 383f45d..e7192af 100644 --- a/Sources/SwiftNetworking/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift +++ b/Sources/SwiftAPIClient/Utils/Coders/MultipartFormData/MultipartFormDataEncoder.swift @@ -32,7 +32,7 @@ public extension ContentEncoder where Self == MultipartFormDataEncoder { public struct MultipartFormDataEncoder: ContentEncoder { /// The content type associated with this encoder, which is `multipart/form-data`. - public var contentType: SwiftNetworking.ContentType { + public var contentType: SwiftAPIClient.ContentType { .multipart(.formData, boundary: boundary) } diff --git a/Sources/SwiftNetworking/Utils/Coders/QueryEncoder.swift b/Sources/SwiftAPIClient/Utils/Coders/QueryEncoder.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/QueryEncoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/QueryEncoder.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/URLQuery/PlainCodingKey.swift b/Sources/SwiftAPIClient/Utils/Coders/URLQuery/PlainCodingKey.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/URLQuery/PlainCodingKey.swift rename to Sources/SwiftAPIClient/Utils/Coders/URLQuery/PlainCodingKey.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/URLQuery/QueryValue.swift b/Sources/SwiftAPIClient/Utils/Coders/URLQuery/QueryValue.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/URLQuery/QueryValue.swift rename to Sources/SwiftAPIClient/Utils/Coders/URLQuery/QueryValue.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/URLQuery/Ref.swift b/Sources/SwiftAPIClient/Utils/Coders/URLQuery/Ref.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/URLQuery/Ref.swift rename to Sources/SwiftAPIClient/Utils/Coders/URLQuery/Ref.swift diff --git a/Sources/SwiftNetworking/Utils/Coders/URLQuery/URLQueryEncoder.swift b/Sources/SwiftAPIClient/Utils/Coders/URLQuery/URLQueryEncoder.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Coders/URLQuery/URLQueryEncoder.swift rename to Sources/SwiftAPIClient/Utils/Coders/URLQuery/URLQueryEncoder.swift diff --git a/Sources/SwiftNetworking/Utils/ConsoleStyle.swift b/Sources/SwiftAPIClient/Utils/ConsoleStyle.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/ConsoleStyle.swift rename to Sources/SwiftAPIClient/Utils/ConsoleStyle.swift diff --git a/Sources/SwiftNetworking/Utils/Error+String.swift b/Sources/SwiftAPIClient/Utils/Error+String.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Error+String.swift rename to Sources/SwiftAPIClient/Utils/Error+String.swift diff --git a/Sources/SwiftNetworking/Utils/NoneLogger.swift b/Sources/SwiftAPIClient/Utils/NoneLogger.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/NoneLogger.swift rename to Sources/SwiftAPIClient/Utils/NoneLogger.swift diff --git a/Sources/SwiftNetworking/Utils/Publisher+Create.swift b/Sources/SwiftAPIClient/Utils/Publisher+Create.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Publisher+Create.swift rename to Sources/SwiftAPIClient/Utils/Publisher+Create.swift diff --git a/Sources/SwiftNetworking/Utils/Publishers+Task.swift b/Sources/SwiftAPIClient/Utils/Publishers+Task.swift similarity index 100% rename from Sources/SwiftNetworking/Utils/Publishers+Task.swift rename to Sources/SwiftAPIClient/Utils/Publishers+Task.swift diff --git a/Sources/SwiftNetworking/Utils/URLSessionDelegateWrapper.swift b/Sources/SwiftAPIClient/Utils/URLSessionDelegateWrapper.swift similarity index 98% rename from Sources/SwiftNetworking/Utils/URLSessionDelegateWrapper.swift rename to Sources/SwiftAPIClient/Utils/URLSessionDelegateWrapper.swift index a2a7519..dce90f8 100644 --- a/Sources/SwiftNetworking/Utils/URLSessionDelegateWrapper.swift +++ b/Sources/SwiftAPIClient/Utils/URLSessionDelegateWrapper.swift @@ -7,7 +7,7 @@ final class SessionDelegateProxy: NSObject, URLSessionDelegate { static let shared = SessionDelegateProxy() var originalDelegate: URLSessionDelegate? { configs?.urlSessionDelegate } - var configs: NetworkClient.Configs? + var configs: APIClient.Configs? override func responds(to aSelector: Selector!) -> Bool { if super.responds(to: aSelector) { diff --git a/Sources/SwiftNetworking/Clients/HTTPPublisher.swift b/Sources/SwiftNetworking/Clients/HTTPPublisher.swift deleted file mode 100644 index 887b6f9..0000000 --- a/Sources/SwiftNetworking/Clients/HTTPPublisher.swift +++ /dev/null @@ -1,16 +0,0 @@ -#if canImport(Combine) -import Combine -import Foundation - -public extension NetworkClientCaller where Result == AnyPublisher, Response == Data { - - static var httpPublisher: NetworkClientCaller { - NetworkClientCaller>.http.map { value in - Publishers.Task { - try await value() - } - .eraseToAnyPublisher() - } - } -} -#endif diff --git a/Tests/SwiftNetworkingTests/EncodersTests/MultipartFormDataTests.swift b/Tests/SwiftAPIClientTests/EncodersTests/MultipartFormDataTests.swift similarity index 98% rename from Tests/SwiftNetworkingTests/EncodersTests/MultipartFormDataTests.swift rename to Tests/SwiftAPIClientTests/EncodersTests/MultipartFormDataTests.swift index b315612..11c7bb1 100644 --- a/Tests/SwiftNetworkingTests/EncodersTests/MultipartFormDataTests.swift +++ b/Tests/SwiftAPIClientTests/EncodersTests/MultipartFormDataTests.swift @@ -1,5 +1,5 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient import XCTest class MultipartFormDataTests: XCTestCase { diff --git a/Tests/SwiftNetworkingTests/Modifiers/AuthModifierTests.swift b/Tests/SwiftAPIClientTests/Modifiers/AuthModifierTests.swift similarity index 91% rename from Tests/SwiftNetworkingTests/Modifiers/AuthModifierTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/AuthModifierTests.swift index 4085a21..c5b53ca 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/AuthModifierTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/AuthModifierTests.swift @@ -1,5 +1,5 @@ import Foundation -@testable import SwiftNetworking +@testable import SwiftAPIClient import XCTest #if canImport(FoundationNetworking) import FoundationNetworking @@ -7,7 +7,7 @@ import FoundationNetworking final class AuthModifierTests: XCTestCase { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) func testAuthEnabled() throws { let client = client.auth(.header("Bearer token")) diff --git a/Tests/SwiftNetworkingTests/Modifiers/ErrorDecodingTests.swift b/Tests/SwiftAPIClientTests/Modifiers/ErrorDecodingTests.swift similarity index 86% rename from Tests/SwiftNetworkingTests/Modifiers/ErrorDecodingTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/ErrorDecodingTests.swift index 49ba3fd..44901ee 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/ErrorDecodingTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/ErrorDecodingTests.swift @@ -1,5 +1,5 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif @@ -10,7 +10,7 @@ final class ErrorDecodingTests: XCTestCase { func testErrorDecoding() throws { let errorJSON = Data(#"{"error": "test_error"}"#.utf8) do { - let _ = try NetworkClient(baseURL: URL(string: "https://example.com")!) + let _ = try APIClient(baseURL: URL(string: "https://example.com")!) .errorDecoder(.decodable(ErrorResponse.self)) .call(.mock(errorJSON), as: .decodable(FakeResponse.self)) XCTFail() diff --git a/Tests/SwiftNetworkingTests/Modifiers/HTTPResponseValidatorTests.swift b/Tests/SwiftAPIClientTests/Modifiers/HTTPResponseValidatorTests.swift similarity index 93% rename from Tests/SwiftNetworkingTests/Modifiers/HTTPResponseValidatorTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/HTTPResponseValidatorTests.swift index c73e7cb..da17984 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/HTTPResponseValidatorTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/HTTPResponseValidatorTests.swift @@ -1,5 +1,5 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif @@ -11,7 +11,7 @@ final class HTTPResponseValidatorTests: XCTestCase { let validator = HTTPResponseValidator.statusCode(200 ... 299) let response = HTTPURLResponse(url: URL(string: "https://example.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)! let data = Data() - let configs = NetworkClient.Configs() + let configs = APIClient.Configs() // Validation should pass for a status code within the range XCTAssertNoThrow(try validator.validate(response, data, configs)) @@ -25,7 +25,7 @@ final class HTTPResponseValidatorTests: XCTestCase { let validator = HTTPResponseValidator.alwaysSuccess let response = HTTPURLResponse(url: URL(string: "https://example.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)! let data = Data() - let configs = NetworkClient.Configs() + let configs = APIClient.Configs() // Validation should always pass without throwing any errors XCTAssertNoThrow(try validator.validate(response, data, configs)) diff --git a/Tests/SwiftNetworkingTests/Modifiers/LogLevelModifierTests.swift b/Tests/SwiftAPIClientTests/Modifiers/LogLevelModifierTests.swift similarity index 70% rename from Tests/SwiftNetworkingTests/Modifiers/LogLevelModifierTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/LogLevelModifierTests.swift index d9ab7bc..cdaa002 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/LogLevelModifierTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/LogLevelModifierTests.swift @@ -1,6 +1,6 @@ import Foundation import Logging -@testable import SwiftNetworking +@testable import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif @@ -9,14 +9,14 @@ import XCTest final class LogLevelModifierTests: XCTestCase { func testLogLevel() { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) let modifiedClient = client.log(level: .debug) XCTAssertEqual(modifiedClient.configs().logLevel, .debug) } func testLogger() { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) let modifiedClient = client.log(level: .info) XCTAssertEqual(modifiedClient.configs().logger.logLevel, .info) diff --git a/Tests/SwiftNetworkingTests/Modifiers/MockResponsesTests.swift b/Tests/SwiftAPIClientTests/Modifiers/MockResponsesTests.swift similarity index 85% rename from Tests/SwiftNetworkingTests/Modifiers/MockResponsesTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/MockResponsesTests.swift index 94e709e..bd72a61 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/MockResponsesTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/MockResponsesTests.swift @@ -1,5 +1,5 @@ import Foundation -@testable import SwiftNetworking +@testable import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif @@ -8,7 +8,7 @@ import XCTest final class MockResponsesTests: XCTestCase { func testMock() throws { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) let mockValue = "Mock Response" let modifiedClient = client.mock(mockValue) diff --git a/Tests/SwiftNetworkingTests/Modifiers/RequestCompressionTests.swift b/Tests/SwiftAPIClientTests/Modifiers/RequestCompressionTests.swift similarity index 71% rename from Tests/SwiftNetworkingTests/Modifiers/RequestCompressionTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/RequestCompressionTests.swift index 22b21f6..ddee3b2 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/RequestCompressionTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/RequestCompressionTests.swift @@ -1,17 +1,17 @@ #if canImport(zlib) import Foundation -@testable import SwiftNetworking +@testable import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif import XCTest -final class NetworkClientCompressionTests: XCTestCase { +final class APIClientCompressionTests: XCTestCase { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testThatRequestCompressorProperlyCalculatesAdler32() throws { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!).compressRequest() + let client = APIClient(baseURL: URL(string: "https://example.com")!).compressRequest() let request = try client.body(Data("Wikipedia".utf8)).request() // From https://en.wikipedia.org/wiki/Adler-32 XCTAssertEqual(request.httpBody, Data([87, 105, 107, 105, 112, 101, 100, 105, 97])) diff --git a/Tests/SwiftNetworkingTests/Modifiers/RequestModifiersTests.swift b/Tests/SwiftAPIClientTests/Modifiers/RequestModifiersTests.swift similarity index 94% rename from Tests/SwiftNetworkingTests/Modifiers/RequestModifiersTests.swift rename to Tests/SwiftAPIClientTests/Modifiers/RequestModifiersTests.swift index 142512f..d5910eb 100644 --- a/Tests/SwiftNetworkingTests/Modifiers/RequestModifiersTests.swift +++ b/Tests/SwiftAPIClientTests/Modifiers/RequestModifiersTests.swift @@ -1,5 +1,5 @@ import Foundation -@testable import SwiftNetworking +@testable import SwiftAPIClient import XCTest #if canImport(FoundationNetworking) import FoundationNetworking @@ -7,7 +7,7 @@ import FoundationNetworking final class RequestModifiersTests: XCTestCase { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) func testPathAppending() throws { @@ -41,7 +41,7 @@ final class RequestModifiersTests: XCTestCase { } func testHeaderUpdating() throws { - let client = NetworkClient(baseURL: URL(string: "https://example.com")!) + let client = APIClient(baseURL: URL(string: "https://example.com")!) let modifiedClient = client .headers(HTTPHeader.accept(.application(.json))) diff --git a/Tests/SwiftNetworkingTests/NetworkClientTests.swift b/Tests/SwiftAPIClientTests/NetworkClientTests.swift similarity index 83% rename from Tests/SwiftNetworkingTests/NetworkClientTests.swift rename to Tests/SwiftAPIClientTests/NetworkClientTests.swift index ce6a21f..c6d77f2 100644 --- a/Tests/SwiftNetworkingTests/NetworkClientTests.swift +++ b/Tests/SwiftAPIClientTests/NetworkClientTests.swift @@ -1,30 +1,30 @@ import Foundation import Logging -@testable import SwiftNetworking +@testable import SwiftAPIClient import XCTest #if canImport(FoundationNetworking) import FoundationNetworking #endif -final class NetworkClientTests: XCTestCase { +final class APIClientTests: XCTestCase { func testInitWithBaseURL() throws { let url = URL(string: "https://example.com")! - let client = NetworkClient(baseURL: url) + let client = APIClient(baseURL: url) let request = try client.request() XCTAssertEqual(request, URLRequest(url: url)) } func testInitWithRequest() throws { let request = URLRequest(url: URL(string: "https://example.com")!) - let client = NetworkClient(request: request) + let client = APIClient(request: request) let resultRequest = try client.request() XCTAssertEqual(request, resultRequest) } func testModifyRequest() throws { let interval: TimeInterval = 30 - let client = NetworkClient.test + let client = APIClient.test .modifyRequest { request in request.timeoutInterval = interval } @@ -33,7 +33,7 @@ final class NetworkClientTests: XCTestCase { } func testWithRequest() throws { - let client = NetworkClient.test + let client = APIClient.test let result = try client.withRequest { request, _ in request.url?.absoluteString == "https://example.com" } @@ -41,7 +41,7 @@ final class NetworkClientTests: XCTestCase { } func testWithConfigs() throws { - let client = NetworkClient.test + let client = APIClient.test let enabled = client .configs(\.testValue, true) .withConfigs(\.testValue) @@ -56,7 +56,7 @@ final class NetworkClientTests: XCTestCase { } func testConfigsOrder() throws { - let client = NetworkClient.test + let client = APIClient.test let (request, configs) = try client .configs(\.intValue, 1) .query { @@ -79,13 +79,13 @@ final class NetworkClientTests: XCTestCase { } func testConfigs() throws { - let enabled = NetworkClient.test + let enabled = APIClient.test .configs(\.testValue, true) .withConfigs(\.testValue) XCTAssertTrue(enabled) - let disabled = NetworkClient.test + let disabled = APIClient.test .configs(\.testValue, false) .withConfigs(\.testValue) @@ -93,7 +93,7 @@ final class NetworkClientTests: XCTestCase { } } -extension NetworkClient.Configs { +extension APIClient.Configs { var testValue: Bool { get { self[\.testValue] ?? false } diff --git a/Tests/SwiftNetworkingTests/TestUtils/Client+Ext.swift b/Tests/SwiftAPIClientTests/TestUtils/Client+Ext.swift similarity index 50% rename from Tests/SwiftNetworkingTests/TestUtils/Client+Ext.swift rename to Tests/SwiftAPIClientTests/TestUtils/Client+Ext.swift index 97d82a2..465eaf8 100644 --- a/Tests/SwiftNetworkingTests/TestUtils/Client+Ext.swift +++ b/Tests/SwiftAPIClientTests/TestUtils/Client+Ext.swift @@ -1,13 +1,13 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif -extension NetworkClient { +extension APIClient { - static var test: NetworkClient { - NetworkClient(baseURL: URL(string: "https://example.com")!) + static var test: APIClient { + APIClient(baseURL: URL(string: "https://example.com")!) } func configs() -> Configs { diff --git a/Tests/SwiftNetworkingTests/TestUtils/TestHTTPClient.swift b/Tests/SwiftAPIClientTests/TestUtils/TestHTTPClient.swift similarity index 69% rename from Tests/SwiftNetworkingTests/TestUtils/TestHTTPClient.swift rename to Tests/SwiftAPIClientTests/TestUtils/TestHTTPClient.swift index a28912c..4e3d23c 100644 --- a/Tests/SwiftNetworkingTests/TestUtils/TestHTTPClient.swift +++ b/Tests/SwiftAPIClientTests/TestUtils/TestHTTPClient.swift @@ -1,5 +1,5 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient #if canImport(FoundationNetworking) import FoundationNetworking #endif @@ -13,9 +13,9 @@ extension HTTPClient { } } -private extension NetworkClient.Configs { +private extension APIClient.Configs { - var testHTTPClient: (URLRequest, NetworkClient.Configs) throws -> (Data, HTTPURLResponse) { + var testHTTPClient: (URLRequest, APIClient.Configs) throws -> (Data, HTTPURLResponse) { get { self[\.testHTTPClient] ?? { _, _ in throw Unimplemented() } } set { self[\.testHTTPClient] = newValue } } @@ -23,10 +23,10 @@ private extension NetworkClient.Configs { private struct Unimplemented: Error {} -extension NetworkClient { +extension APIClient { func httpTest( - test: @escaping (URLRequest, NetworkClient.Configs) throws -> Void = { _, _ in } + test: @escaping (URLRequest, APIClient.Configs) throws -> Void = { _, _ in } ) async throws { try await httpTest { try test($0, $1) @@ -35,7 +35,7 @@ extension NetworkClient { } func httpTest( - test: @escaping (URLRequest, NetworkClient.Configs) throws -> (Data, HTTPURLResponse) + test: @escaping (URLRequest, APIClient.Configs) throws -> (Data, HTTPURLResponse) ) async throws { try await configs(\.testHTTPClient) { try test($0, $1) @@ -45,7 +45,7 @@ extension NetworkClient { } func httpTest( - test: @escaping (URLRequest, NetworkClient.Configs) throws -> Data + test: @escaping (URLRequest, APIClient.Configs) throws -> Data ) async throws { try await httpTest { let data = try test($0, $1) diff --git a/Tests/SwiftNetworkingTests/URLQueryEncoderTests.swift b/Tests/SwiftAPIClientTests/URLQueryEncoderTests.swift similarity index 99% rename from Tests/SwiftNetworkingTests/URLQueryEncoderTests.swift rename to Tests/SwiftAPIClientTests/URLQueryEncoderTests.swift index 2ea336b..fc7ae08 100644 --- a/Tests/SwiftNetworkingTests/URLQueryEncoderTests.swift +++ b/Tests/SwiftAPIClientTests/URLQueryEncoderTests.swift @@ -1,12 +1,12 @@ import Foundation -import SwiftNetworking +import SwiftAPIClient import XCTest final class URLEncodedFormQueryEncoderTests: XCTestCase { func testThatQueryIsBodyEncodedAndProperContentTypeIsSetForPOSTRequest() throws { // Given - var client = NetworkClient.test.bodyEncoder(.formURL) + var client = APIClient.test.bodyEncoder(.formURL) // When client = client.body(TestQuery()) @@ -19,7 +19,7 @@ final class URLEncodedFormQueryEncoderTests: XCTestCase { func testThatQueryIsBodyEncodedButContentTypeIsNotSetWhenRequestAlreadyHasContentType() throws { // Given - var client = NetworkClient.test.header(.contentType, "type").bodyEncoder(.formURL) + var client = APIClient.test.header(.contentType, "type").bodyEncoder(.formURL) // When client = client.body(TestQuery()) @@ -1007,7 +1007,7 @@ struct OrderedDict: ExpressibleByDictionaryLiteral, Encodable { } func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: SwiftNetworkingTests.Key.self) + var container = encoder.container(keyedBy: SwiftAPIClientTests.Key.self) for (key, value) in dict { try container.encode(value, forKey: .init(key)) }