diff --git a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
index 706eede..919434a 100644
--- a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
+++ b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
@@ -2,6 +2,6 @@
+ location = "self:">
diff --git a/Package.resolved b/Package.resolved
new file mode 100644
index 0000000..3cadc13
--- /dev/null
+++ b/Package.resolved
@@ -0,0 +1,16 @@
+{
+ "object": {
+ "pins": [
+ {
+ "package": "PublisherKit",
+ "repositoryURL": "https://github.com/ragzy15/PublisherKit",
+ "state": {
+ "branch": null,
+ "revision": "ad211780f0f532a473e3d5d1cef2a2644024d7c4",
+ "version": "1.0.0"
+ }
+ }
+ ]
+ },
+ "version": 1
+}
diff --git a/Package.swift b/Package.swift
index 20f668c..68f8439 100644
--- a/Package.swift
+++ b/Package.swift
@@ -18,6 +18,7 @@ let package = Package(
targets: ["NetworkKit"]),
],
dependencies: [
+ .package(url: "https://github.com/ragzy15/PublisherKit", from: .init(1, 0, 0))
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
@@ -26,7 +27,7 @@ let package = Package(
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "NetworkKit",
- dependencies: []),
+ dependencies: ["PublisherKit"]),
.testTarget(
name: "NetworkKitTests",
dependencies: ["NetworkKit"]),
diff --git a/Sources/NetworkKit/Create Request/Create Request.swift b/Sources/NetworkKit/Create Request/Create Request.swift
index c0df1ff..4a9841e 100644
--- a/Sources/NetworkKit/Create Request/Create Request.swift
+++ b/Sources/NetworkKit/Create Request/Create Request.swift
@@ -15,7 +15,7 @@ public struct CreateRequest {
public let request: URLRequest
- public init?(with connection: ConnectionRepresentable, query urlQuery: URLQuery?) {
+ public init?(with connection: ConnectionRepresentable, query urlQuery: Set, body: Data?, headers: HTTPHeaderParameters) {
var components = URLComponents()
components.scheme = connection.scheme.rawValue
@@ -26,15 +26,15 @@ public struct CreateRequest {
components.host = (subURL.isEmpty ? subURL : subURL + ".") + connection.host.host
components.path = endPoint + connection.path
- var queryItems: [URLQueryItem] = []
- queryItems.addURLQuery(query: urlQuery)
+ var queryItems = Set()
queryItems.addURLQuery(query: connection.defaultQuery)
queryItems.addURLQuery(query: connection.host.defaultUrlQuery)
+ queryItems = queryItems.union(urlQuery)
let method = connection.method
if !queryItems.isEmpty {
- components.queryItems = queryItems
+ components.queryItems = Array(queryItems)
}
guard let url = components.url else {
@@ -47,15 +47,15 @@ public struct CreateRequest {
let defaultHeaderFields = connection.host.defaultHeaders
let connectionHeaderFields = connection.httpHeaders
- let headerFields = defaultHeaderFields.merging(connectionHeaderFields) { (_, new) in new }
+ var headerFields = defaultHeaderFields.merging(connectionHeaderFields) { (_, new) in new }
+ headerFields.merge(headers) { (_, new) in new }
if !headerFields.isEmpty {
urlRequest.allHTTPHeaderFields = headerFields
}
+
+ urlRequest.httpBody = body
request = urlRequest
- #if DEBUG
- DebugPrint.logAPIRequest(request: request, apiName: connection.name)
- #endif
}
}
diff --git a/Sources/NetworkKit/Debug Loging/Debug Logging.swift b/Sources/NetworkKit/Debug Loging/Debug Logging.swift
deleted file mode 100644
index dc32772..0000000
--- a/Sources/NetworkKit/Debug Loging/Debug Logging.swift
+++ /dev/null
@@ -1,42 +0,0 @@
-//
-// DebugLogging.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-typealias DebugPrint = PilotDebugLogs
-
-/// Allows Logs to be Printed in Debug Console.
-public struct PilotDebugLogs {
-
- /// Enabled Network debug logs to be printed in debug console.
- /// Default value is `true`
- public static var isEnabled = true
-
- // MARK: - DEBUG LOGS HANDLER
-
- /// Writes the textual representations of the given items into the standard output.
- /// - Parameter value: String to be printed on console.
- /// - Parameter flag: If the value should be printed on console
- static func print(_ value: String, shouldPrint flag: Bool = true) {
- if DebugPrint.isEnabled, flag {
- Swift.print(value)
- }
- }
-
- static func logAPIRequest(request: URLRequest, apiName: String?) {
- print(
- """
- ------------------------------------------------------------
- API Call Request for:
- Name: \(apiName ?? "nil")
- \(request.debugDescription)
-
- """
- )
- }
-}
diff --git a/Sources/NetworkKit/Debug Loging/NKLogger.swift b/Sources/NetworkKit/Debug Loging/NKLogger.swift
new file mode 100644
index 0000000..9bcb0e5
--- /dev/null
+++ b/Sources/NetworkKit/Debug Loging/NKLogger.swift
@@ -0,0 +1,226 @@
+//
+// NKLogger.swift
+// NetworkKit
+//
+// Created by Raghav Ahuja on 18/10/19.
+// Copyright © 2019 Raghav Ahuja. All rights reserved.
+//
+
+import Foundation
+
+final public class NKLogger {
+
+ /// Allows Logs to be Printed in Debug Console.
+ /// Default value is `true`
+ public var isLoggingEnabled: Bool = true
+
+ public static let `default` = NKLogger()
+
+ /**
+ Creates a `NKLogger`.
+ */
+ public init() { }
+
+ /**
+ Writes the textual representations of the given items into the standard output.
+
+ - parameter items: Zero or more items to print..
+ - parameter separator: A string to print between each item. The default is a single space (" ").
+ - parameter terminator: The string to print after all items have been printed. The default is a newline ("\n").
+
+ */
+ func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
+ #if DEBUG
+ guard NKConfiguration.allowLoggingOnAllSessions, isLoggingEnabled else { return }
+ Swift.print(items, separator: separator, terminator: terminator)
+ #endif
+ }
+
+ /**
+ Writes the textual representations of the given items most suitable for debugging into the standard output.
+
+ - parameter items: Zero or more items to print.
+ - parameter separator: A string to print between each item. The default is a single space (" ").
+ - parameter terminator: The string to print after all items have been printed. The default is a newline ("\n").
+
+ */
+ func debugPrint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
+ #if DEBUG
+ guard NKConfiguration.allowLoggingOnAllSessions, isLoggingEnabled else { return }
+ Swift.debugPrint(items, separator: separator, terminator: terminator)
+ #endif
+ }
+
+ /**
+ Handles APIRequest logging sent by the `NetworkKit`.
+
+ - parameter request: URLRequest
+ - parameter apiName: API name.
+ */
+ func logAPIRequest(request: URLRequest?, apiName: String?) {
+ #if DEBUG
+ guard NKConfiguration.allowLoggingOnAllSessions, isLoggingEnabled else { return }
+
+ Swift.print(
+ """
+ ------------------------------------------------------------
+ API Call Request for:
+ Name: \(apiName ?? "nil")
+ \(request?.debugDescription ?? "")
+
+ """
+ )
+ #endif
+ }
+
+ /**
+ Print JSON sent by the `NetworkKit`.
+
+ - parameter data: Input Type to be printed
+ - parameter apiName: API name.
+ */
+ func printJSON(data: Input, apiName: String) {
+ #if DEBUG
+ guard NKConfiguration.allowLoggingOnAllSessions, isLoggingEnabled else { return }
+ guard let data = data as? Data else {
+ return
+ }
+
+ do {
+ let object = try JSONSerialization.jsonObject(with: data, options: [])
+ let newData = try JSONSerialization.data(withJSONObject: object, options: .prettyPrinted)
+
+// Swift.print(
+// """
+// ------------------------------------------------------------
+// Printing JSON for:
+// API Name: \(apiName)
+// JSON:
+//
+ // """)
+ Swift.print("""
+ ------------------------------------------------------------
+ JSON:
+
+ """)
+ Swift.print(String(data: newData, encoding: .utf8) ?? "nil")
+ Swift.print("------------------------------------------------------------")
+
+ } catch {
+
+ }
+ #endif
+ }
+
+ /**
+ Handles errors sent by the `NetworkKit`.
+
+ - parameter error: Error occurred.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inline(__always)
+ func log(error: Error, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
+ #if DEBUG
+ guard NKConfiguration.allowLoggingOnAllSessions, isLoggingEnabled else { return }
+
+ Swift.print("⚠️ [NetworkKit: Error] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(error as NSError)\n")
+ #endif
+ }
+
+ /**
+ Handles assertions made throughout the `NetworkKit`.
+
+ - parameter condition: Assertion condition.
+ - parameter message: Assertion failure message.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inline(__always)
+ func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
+
+ #if DEBUG
+ let condition = condition()
+
+ if condition { return }
+
+ let message = message()
+
+ Swift.print("❗ [NetworkKit: Assertion Failure] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(message)\n")
+ Swift.assert(condition, message, file: file, line: line)
+ #endif
+ }
+
+ /**
+ Handles assertion failures made throughout the `NetworkKit`.
+
+ - parameter message: Assertion failure message.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inlinable public func assertionFailure(_ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
+ let message = message()
+ Swift.print("❗ [NetworkKit: Assertion Failure] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(message)\n")
+ Swift.assertionFailure(message, file: file, line: line)
+ }
+
+ /**
+ Handles precondition failures made throughout the `NetworkKit`.
+
+ - parameter message: Assertion failure message.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inlinable public func preconditionFailure(_ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line, function: StaticString = #function) -> Never {
+ let message = message()
+ Swift.print("❗ [NetworkKit: Assertion Failure] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(message)\n")
+ Swift.preconditionFailure(message, file: file, line: line)
+ }
+
+ /**
+ Handles preconditions made throughout the `NetworkKit`.
+
+ - parameter condition: Precondition to be satisfied.
+ - parameter message: Precondition failure message.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inline(__always)
+ func precondition(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
+
+ #if DEBUG
+ let condition = condition()
+
+ if condition { return }
+
+ let message = message()
+
+ Swift.print("❗ [NetworkKit: Precondition Failure] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(message)\n")
+ Swift.preconditionFailure(message, file: file, line: line)
+ #endif
+ }
+
+ /**
+ Handles fatal errors made throughout the `NetworkKit`.
+ - Important: Implementers should guarantee that this function doesn't return, either by calling another `Never` function such as `fatalError()` or `abort()`, or by raising an exception.
+
+ - parameter message: Fatal error message.
+ - parameter file: Source file name.
+ - parameter line: Source line number.
+ - parameter function: Source function name.
+ */
+ @inline(__always)
+ func fatalError(_ message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) -> Never {
+
+ #if DEBUG
+ let message = message()
+ Swift.print("❗ [NetworkKit: Fatal Error] \((String(describing: file) as NSString).lastPathComponent):\(line) \(function)\n ↪︎ \(message)\n")
+ Swift.fatalError(message, file: file, line: line)
+ #endif
+ }
+}
diff --git a/Sources/NetworkKit/Errors/Business Error.swift b/Sources/NetworkKit/Errors/Business Error.swift
deleted file mode 100644
index fd6f8d9..0000000
--- a/Sources/NetworkKit/Errors/Business Error.swift
+++ /dev/null
@@ -1,29 +0,0 @@
-//
-// BusinessError.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-/// Personal / Business / Server Errors
-enum BusinessError: LocalizedError {
-
- case errorModel(ErrorModel, Int)
-
- var localizedDescription: String {
- switch self {
- case .errorModel(let model, _):
- return model.message ?? ""
- }
- }
-
- var errorCode: Int {
- switch self {
- case .errorModel(let model, let httpStatusCode):
- return model.code ?? httpStatusCode
- }
- }
-}
diff --git a/Sources/NetworkKit/Errors/HTTP Error.swift b/Sources/NetworkKit/Errors/HTTP Error.swift
deleted file mode 100644
index f5f8c85..0000000
--- a/Sources/NetworkKit/Errors/HTTP Error.swift
+++ /dev/null
@@ -1,135 +0,0 @@
-//
-// HTTPStatusCodes.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-/// HTTP Status Codes, obtained in `HTTPURLResponse`
-enum HTTPStatusCode: Int, LocalizedError {
-
- case `continue` = 100
- case switchingProtocols = 101
- case processing = 102
- case earlyHints = 103
-
-
- case ok = 200
- case created = 201
- case accepted = 202
- case nonAuthoritativeInformation = 203
- case noContent = 204
- case resetContent = 205
- case partialContent = 206
- case multiStatus = 207
- case alreadyReported = 208
- case imUsed = 226
-
-
- case multipleChoices = 300
- case movedPermanently = 301
- case found = 302
- case seeOther = 303
- case notModified = 304
- case useProxy = 305
- case temporaryRedirect = 307
- case permanentRedirect = 308
-
-
- case badRequest = 400
- case unauthorized = 401
- case paymentRequired = 402
- case forbidden = 403
- case notFound = 404
- case methodNotAllowed = 405
- case notAcceptable = 406
- case proxyAuthenticationRequired = 407
- case requestTimeout = 408
- case conflict = 409
- case gone = 410
- case lengthRequired = 411
- case preconditionFailed = 412
- case payloadTooLarge = 413
- case uriTooLong = 414
- case unsupportedMediaType = 415
- case rangeNotSatisfiable = 416
- case expectationFailed = 417
-
- case imATeapot = 418
- case misdirectedRequest = 421
- case unprocessableEntity = 422
- case locked = 423
- case failedDependency = 424
- case tooEarly = 425
- case upgradeRequired = 426
- case preconditionRequired = 428
- case tooManyRequests = 429
- case requestHeaderFieldsTooLarge = 431
- case iisLoginTimeout = 440
- case nginxNoResponse = 444
- case iisRetryWith = 449
- case blockedByWindowsParentalControls = 450
- case unavailableForLegalReasons = 451
- case nginxSSLCertificateError = 495
- case nginxSSLCertificateRequired = 496
-
- case nginxHTTPToHTTPS = 497
- case tokenExpired = 498
- case nginxClientClosedRequest = 499
-
-
- case internalServerError = 500
- case notImplemented = 501
- case badGateway = 502
- case serviceUnavailable = 503
- case gatewayTimeout = 504
- case httpVersionNotSupported = 505
- case variantAlsoNegotiates = 506
- case insufficientStorage = 507
- case loopDetected = 508
- case bandwidthLimitExceeded = 509
- case notExtended = 510
- case networkAuthenticationRequired = 511
- case siteIsFrozen = 530
- case networkConnectTimeoutError = 599
-
- /// Retrieve the localized description for this error.
- var localizedDescription: String {
- return HTTPURLResponse.localizedString(forStatusCode: rawValue)
- }
-
- var errorDescription: String? {
- return HTTPURLResponse.localizedString(forStatusCode: rawValue)
- }
-}
-
-extension HTTPStatusCode {
- /// Informational - Request received, continuing process.
- var isInformational: Bool {
- return isIn(range: 100...199)
- }
- /// Success - The action was successfully received, understood, and accepted.
- var isSuccess: Bool {
- return isIn(range: 200...299)
- }
- /// Redirection - Further action must be taken in order to complete the request.
- var isRedirection: Bool {
- return isIn(range: 300...399)
- }
- /// Client Error - The request contains bad syntax or cannot be fulfilled.
- var isClientError: Bool {
- return isIn(range: 400...499)
- }
- /// Server Error - The server failed to fulfill an apparently valid request.
- var isServerError: Bool {
- return isIn(range: 500...599)
- }
-
- /// - returns: `true` if the status code is in the provided range, false otherwise.
- private func isIn(range: ClosedRange) -> Bool {
- return range.contains(rawValue)
- }
-}
diff --git a/Sources/NetworkKit/Extensions/NSError+Extension.swift b/Sources/NetworkKit/Errors/NSError.swift
similarity index 65%
rename from Sources/NetworkKit/Extensions/NSError+Extension.swift
rename to Sources/NetworkKit/Errors/NSError.swift
index b970565..4708a1f 100644
--- a/Sources/NetworkKit/Extensions/NSError+Extension.swift
+++ b/Sources/NetworkKit/Errors/NSError.swift
@@ -1,8 +1,8 @@
//
-// NSError+Extension.swift
+// NSError.swift
// NetworkKit
//
-// Created by Raghav Ahuja on 21/11/19.
+// Created by Raghav Ahuja on 18/10/19.
// Copyright © 2019 Raghav Ahuja. All rights reserved.
//
@@ -10,19 +10,21 @@ import Foundation
extension NSError {
+ public static var networkKitErrorDomain: String { "NKErrorDomain" }
+
static func cancelled(for url: URL?) -> NSError {
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "User cancelled the task for url: \(url?.absoluteString ?? "nil")."]
if let url = url {
userInfo[NSURLErrorFailingURLErrorKey] = url
}
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: userInfo)
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorCancelled, userInfo: userInfo)
return error
}
static func badServerResponse(for url: URL) -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorBadServerResponse, userInfo: [
NSURLErrorFailingURLErrorKey: url,
NSLocalizedDescriptionKey: "Bad server response for request : \(url.absoluteString)"
])
@@ -30,8 +32,17 @@ extension NSError {
return error
}
+ static func badURL(for urlString: String?) -> NSError {
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorBadURL, userInfo: [
+ NSURLErrorFailingURLStringErrorKey: urlString ?? "nil",
+ NSLocalizedDescriptionKey: "Invalid URL provied."
+ ])
+
+ return error
+ }
+
static func resourceUnavailable(for url: URL) -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorResourceUnavailable, userInfo: [
NSURLErrorFailingURLErrorKey: url,
NSLocalizedDescriptionKey: "A requested resource couldn’t be retrieved from url: \(url.absoluteString)."
])
@@ -45,13 +56,13 @@ extension NSError {
userInfo[NSURLErrorFailingURLErrorKey] = url
}
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorUnsupportedURL, userInfo: userInfo)
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorUnsupportedURL, userInfo: userInfo)
return error
}
static func zeroByteResource(for url: URL) -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorZeroByteResource, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorZeroByteResource, userInfo: [
NSURLErrorFailingURLErrorKey: url,
NSLocalizedDescriptionKey: "A server reported that a URL has a non-zero content length, but terminated the network connection gracefully without sending any data."
])
@@ -60,7 +71,7 @@ extension NSError {
}
static func cannotDecodeContentData(for url: URL) -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotDecodeContentData, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorCannotDecodeContentData, userInfo: [
NSURLErrorFailingURLErrorKey: url,
NSLocalizedDescriptionKey: "Content data received during a connection request had an unknown content encoding."
])
@@ -69,7 +80,7 @@ extension NSError {
}
static func cannotDecodeRawData(for url: URL) -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotDecodeRawData, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorCannotDecodeRawData, userInfo: [
NSURLErrorFailingURLErrorKey: url,
NSLocalizedDescriptionKey: "Content data received during a connection request had an unknown content encoding."
])
@@ -83,13 +94,13 @@ extension NSError {
userInfo[NSURLErrorFailingURLErrorKey] = url
}
- let error = NSError(domain: NSURLErrorDomain, code: NSUserCancelledError, userInfo: userInfo)
+ let error = NSError(domain: networkKitErrorDomain, code: NSUserCancelledError, userInfo: userInfo)
return error
}
static func unkown() -> NSError {
- let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: [
+ let error = NSError(domain: networkKitErrorDomain, code: NSURLErrorUnknown, userInfo: [
NSLocalizedDescriptionKey: "An Unknown Occurred."
])
diff --git a/Sources/NetworkKit/Extensions/Dictionary+Extension.swift b/Sources/NetworkKit/Extensions/Dictionary+Extension.swift
deleted file mode 100644
index 38bfeaf..0000000
--- a/Sources/NetworkKit/Extensions/Dictionary+Extension.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// Dictionary+Extension.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-extension Dictionary {
-
- var prettyPrint: String {
- let prefix = isEmpty ? "" : "\n"
- var printString = "\(prefix)["
-
- for (key, value) in self {
- let itemString = "\n\t\(key): \(value),"
- printString.append(itemString)
- }
-
- let postfix = isEmpty ? " " : "\n"
- printString.append("\(postfix)]")
-
- return printString
- }
-}
-
-extension Dictionary where Value: OptionalDelegate {
-
- var prettyPrint: String {
- let prefix = isEmpty ? "" : "\n"
- var printString = "\(prefix)["
-
- for (key, value) in self {
- let optionalValue = value.unwrappedValue()
- let value = optionalValue == nil ? "nil" : "\(optionalValue!)"
-
- let itemString = "\n\t\(key): \(value),"
- printString.append(itemString)
- }
-
- let postfix = isEmpty ? " " : "\n"
- printString.append("\(postfix)]")
-
- return printString
- }
-}
diff --git a/Sources/NetworkKit/Extensions/JSONDecoder+Extension.swift b/Sources/NetworkKit/Extensions/JSONDecoder+Extension.swift
deleted file mode 100644
index 79b8a8d..0000000
--- a/Sources/NetworkKit/Extensions/JSONDecoder+Extension.swift
+++ /dev/null
@@ -1,14 +0,0 @@
-//
-// JSONDecoder+Extension.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 18/11/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-extension JSONDecoder: NetworkDecoder {
-
- public typealias Input = Data
-}
diff --git a/Sources/NetworkKit/Extensions/Optional+Extension.swift b/Sources/NetworkKit/Extensions/Optional+Extension.swift
deleted file mode 100644
index 07f1b81..0000000
--- a/Sources/NetworkKit/Extensions/Optional+Extension.swift
+++ /dev/null
@@ -1,23 +0,0 @@
-//
-// Optional+Extension.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-protocol OptionalDelegate {
-
- associatedtype Wrapped
-
- func unwrappedValue() -> Wrapped?
-}
-
-extension Optional: OptionalDelegate {
-
- func unwrappedValue() -> Wrapped? {
- return self
- }
-}
diff --git a/Sources/NetworkKit/Extensions/Array+Extension.swift b/Sources/NetworkKit/Extensions/Set+Extension.swift
similarity index 83%
rename from Sources/NetworkKit/Extensions/Array+Extension.swift
rename to Sources/NetworkKit/Extensions/Set+Extension.swift
index a420376..63b79dc 100644
--- a/Sources/NetworkKit/Extensions/Array+Extension.swift
+++ b/Sources/NetworkKit/Extensions/Set+Extension.swift
@@ -1,5 +1,5 @@
//
-// Array+Extension.swift
+// Set+Extension.swift
// NetworkKit
//
// Created by Raghav Ahuja on 15/10/19.
@@ -8,14 +8,14 @@
import Foundation
-extension Array where Element == URLQueryItem {
+extension Set where Element == URLQueryItem {
mutating func addURLQuery(query urlQuery: URLQuery?) {
if let urlQuery = urlQuery {
for query in urlQuery {
let queryItem = URLQueryItem(name: query.key, value: query.value)
if !self.contains(queryItem) {
- self.append(queryItem)
+ insert(queryItem)
}
}
}
diff --git a/Sources/NetworkKit/Extensions/URL+Extension.swift b/Sources/NetworkKit/Extensions/URL+Extension.swift
deleted file mode 100644
index e20dad4..0000000
--- a/Sources/NetworkKit/Extensions/URL+Extension.swift
+++ /dev/null
@@ -1,19 +0,0 @@
-//
-// URL+Extension.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-extension URL {
-
- var parameters: URLQuery {
- guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false) else {
- return [:]
- }
- return components.queryItems?.toDictionary ?? [:]
- }
-}
diff --git a/Sources/NetworkKit/Extensions/URLRequest+Extension.swift b/Sources/NetworkKit/Extensions/URLRequest+Extension.swift
deleted file mode 100644
index b75db4f..0000000
--- a/Sources/NetworkKit/Extensions/URLRequest+Extension.swift
+++ /dev/null
@@ -1,27 +0,0 @@
-//
-// URLRequest+Extension.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 15/10/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-extension URLRequest {
-
- var debugDescription: String {
- """
- ------------------------------------------------------------
- Request Method: \(httpMethod ?? "nil")
- Request URL: \(url?.absoluteString ?? "nil")
-
- Request Parameters: \((url?.parameters ?? [:]).prettyPrint)
-
- Request Headers: \((allHTTPHeaderFields ?? [:]).prettyPrint)
-
- Request HTTPBody: \(httpBody?.debugDescription ?? "nil")
- ------------------------------------------------------------
- """
- }
-}
diff --git a/Sources/NetworkKit/Kit/NKAnyCancellable/NKAnyCancellable.swift b/Sources/NetworkKit/Kit/NKAnyCancellable/NKAnyCancellable.swift
deleted file mode 100644
index 7984b62..0000000
--- a/Sources/NetworkKit/Kit/NKAnyCancellable/NKAnyCancellable.swift
+++ /dev/null
@@ -1,33 +0,0 @@
-//
-// NKAnyCancellable.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 25/11/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-public class NKAnyCancellable: NKCancellable {
-
- let block: () -> Void
-
- /// Initializes the cancellable object with the given cancel-time closure.
- ///
- /// - Parameter cancel: A closure that the `cancel()` method executes.
- public init(cancel: @escaping () -> Void) {
- block = cancel
- }
-
- public init(_ canceller: C) {
- block = canceller.cancel
- }
-
- deinit {
- cancel()
- }
-
- public func cancel() {
- block()
- }
-}
diff --git a/Sources/NetworkKit/Kit/NKQueue/NKQueue.swift b/Sources/NetworkKit/Kit/NKQueue/NKQueue.swift
deleted file mode 100644
index 297203a..0000000
--- a/Sources/NetworkKit/Kit/NKQueue/NKQueue.swift
+++ /dev/null
@@ -1,51 +0,0 @@
-//
-// NKQueue.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 18/11/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-public final class NKQueue {
-
- /// A queue that regulates the execution of operations.
- /// It is a serial queue, that has `quality of service` of `utility`.
- private let operationQueue: OperationQueue
-
- let request: URLRequest?
-
- let apiName: String
-
- var operations: [Operation] {
- operationQueue.operations
- }
-
- var isSuspended: Bool {
- get { operationQueue.isSuspended }
- set { operationQueue.isSuspended = newValue }
- }
-
- init(operationQueue: OperationQueue, request: URLRequest?, apiName: String?) {
- self.operationQueue = operationQueue
- self.request = request
- self.apiName = apiName ?? request?.url?.absoluteString ?? "nil"
- }
-
- deinit {
- operationQueue.cancelAllOperations()
- }
-
- func addOperation(_ op: Operation) {
- operationQueue.addOperation(op)
- }
-
- func addOperation(_ block: @escaping () -> Void) {
- operationQueue.addOperation(block)
- }
-
- func cancelAllOperations() {
- operationQueue.cancelAllOperations()
- }
-}
diff --git a/Sources/NetworkKit/Kit/NKResult/NKResult.swift b/Sources/NetworkKit/Kit/NKResult/NKResult.swift
deleted file mode 100644
index b78952c..0000000
--- a/Sources/NetworkKit/Kit/NKResult/NKResult.swift
+++ /dev/null
@@ -1,25 +0,0 @@
-//
-// NKResult.swift
-// NetworkKit
-//
-// Created by Raghav Ahuja on 18/11/19.
-// Copyright © 2019 Raghav Ahuja. All rights reserved.
-//
-
-import Foundation
-
-public final class NKResult