Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
otaviocc committed Oct 24, 2021
0 parents commit c7d75ae
Show file tree
Hide file tree
Showing 15 changed files with 346 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Otavio Cordeiro

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "MicroClient",
platforms: [
.macOS(.v11), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)
],
products: [
.library(
name: "MicroClient",
targets: ["MicroClient"]
)
],
dependencies: [],
targets: [
.target(
name: "MicroClient",
dependencies: []
)
]
)
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# MicroClient

A description of this package.
21 changes: 21 additions & 0 deletions Sources/MicroClient/Extensions/URLComponents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation

extension URL {

static func makeURL<RequestModel, ResponseModel>(
configuration: NetworkConfiguration,
networkRequest: NetworkRequest<RequestModel, ResponseModel>
) throws -> URL {
var components = URLComponents()

components.scheme = configuration.scheme
components.host = configuration.hostname
components.path = networkRequest.path
components.queryItems = networkRequest.queryItems

return try unwrap(
value: components.url,
error: NetworkClientError.malformedURL
)
}
}
26 changes: 26 additions & 0 deletions Sources/MicroClient/Extensions/URLRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation

extension URLRequest {

static func makeURLRequest<RequestModel, ResponseModel>(
configuration: NetworkConfiguration,
networkRequest: NetworkRequest<RequestModel, ResponseModel>
) throws -> URLRequest? {
let url = try URL.makeURL(
configuration: configuration,
networkRequest: networkRequest
)

var request = URLRequest(url: url)
request.httpMethod = networkRequest.method.rawValue
request.httpBody = try networkRequest.body
.map {
try networkRequest.encode(
payload: $0,
defaultEncoder: configuration.defaultEncoder
)
}

return request
}
}
25 changes: 25 additions & 0 deletions Sources/MicroClient/Extensions/Unwrap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Combine

func unwrap<T>(
value: T?,
error: Error
) throws -> T {
guard let value = value else {
throw error
}

return value
}

extension Publisher {

func unwrap<T>(
with error: Failure
) -> Publishers.FlatMap<Result<T, Self.Failure>.Publisher, Self> where Output == T? {
flatMap { unwrapped in
unwrapped.map { value in
Result.success(value).publisher
} ?? Result.failure(error).publisher
}
}
}
9 changes: 9 additions & 0 deletions Sources/MicroClient/HTTPMethod.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Foundation

public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case delete = "DELETE"
case put = "PUT"
case patch = "PATCH"
}
77 changes: 77 additions & 0 deletions Sources/MicroClient/NetworkClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import Combine
import Foundation

public protocol NetworkClientProtocol {

func run<RequestModel, ResponseModel>(
_ networkRequest: NetworkRequest<RequestModel, ResponseModel>
) -> AnyPublisher<NetworkResponse<ResponseModel>, Error>
}

public final class NetworkClient: NetworkClientProtocol {

// MARK: - Properties

private let configuration: NetworkConfiguration

// MARK: - Life cycle

public init(
configuration: NetworkConfiguration
) {
self.configuration = configuration
}

// MARK: - Public

public func run<RequestModel, ResponseModel>(
_ networkRequest: NetworkRequest<RequestModel, ResponseModel>
) -> AnyPublisher<NetworkResponse<ResponseModel>, Error> {
urlRequestPublisher(networkRequest: networkRequest)
.flatMap { request in
self.requestPublisher(
urlRequest: request,
networkRequest: networkRequest
)
}
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}

// MARK: - Private

private func urlRequestPublisher<RequestModel, ResponseModel>(
networkRequest: NetworkRequest<RequestModel, ResponseModel>
) -> AnyPublisher<URLRequest, Error> {
Result {
try URLRequest.makeURLRequest(
configuration: configuration,
networkRequest: networkRequest
)
}
.publisher
.unwrap(with: NetworkClientError.malformedURLRequest)
.compactMap { [configuration] request in
configuration.interceptor?(request)
}
.eraseToAnyPublisher()
}

private func requestPublisher<RequestModel, ResponseModel>(
urlRequest: URLRequest,
networkRequest: NetworkRequest<RequestModel, ResponseModel>
) -> AnyPublisher<NetworkResponse<ResponseModel>, Error> {
configuration.session
.dataTaskPublisher(for: urlRequest)
.tryMap { [configuration] result in
NetworkResponse(
value: try networkRequest.decode(
data: result.data,
defaultDecoder: configuration.defaultDecoder
),
response: result.response
)
}
.eraseToAnyPublisher()
}
}
6 changes: 6 additions & 0 deletions Sources/MicroClient/NetworkClientError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foundation

public enum NetworkClientError: Error {
case malformedURL
case malformedURLRequest
}
40 changes: 40 additions & 0 deletions Sources/MicroClient/NetworkConfiguration.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Foundation

public final class NetworkConfiguration {

/// The session used to perform the network requests.
public let session: URLSession

/// The default JSON decoder. It can be overwritten by
/// individual requests, if necessary.
public let defaultDecoder: JSONDecoder

/// The default JSON encoder. It can be overwritten by
/// individual requests, if necessary.
public let defaultEncoder: JSONEncoder

/// The scheme component of the base URL.
public let scheme: String

/// The host component of the base URL.
public let hostname: String

/// The interceptor called right before performing the
/// network request. Can be used to modify the `URLRequest`
/// if necessary.
public var interceptor: ((URLRequest) -> URLRequest)?

public init(
session: URLSession,
defaultDecoder: JSONDecoder,
defaultEncoder: JSONEncoder,
scheme: String,
hostname: String
) {
self.session = session
self.defaultDecoder = defaultDecoder
self.defaultEncoder = defaultEncoder
self.scheme = scheme
self.hostname = hostname
}
}
79 changes: 79 additions & 0 deletions Sources/MicroClient/NetworkRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import Combine
import Foundation

public struct NetworkRequest<
RequestModel,
ResponseModel
> where RequestModel: Encodable, ResponseModel: Decodable {

// MARK: - Properties

public let path: String
public let method: HTTPMethod
public var parameters: [String: String]?
public var body: RequestModel?
public var decoder: JSONDecoder?
public var encoder: JSONEncoder?

// MARK: - Life cycle

public init(
path: String,
method: HTTPMethod,
parameters: [String : String]? = nil,
body: RequestModel? = nil,
decoder: JSONDecoder? = nil,
encoder: JSONEncoder? = nil
) {
self.path = path
self.method = method
self.parameters = parameters
self.body = body
self.decoder = decoder
self.encoder = encoder
}
}

// MARK: - Query Items

extension NetworkRequest {

public var queryItems: [URLQueryItem]? {
parameters?.compactMap { parameter in
URLQueryItem(
name: parameter.key,
value: parameter.value
)
}
}
}

// MARK: - HTTP Body

extension NetworkRequest {

public func encode(
payload: RequestModel,
defaultEncoder: JSONEncoder
) throws -> Data {
let encoder = encoder ?? defaultEncoder
return try encoder.encode(payload)
}
}

// MARK: - Decode

extension NetworkRequest {

public func decode(
data: Data,
defaultDecoder: JSONDecoder
) throws -> ResponseModel {
let decoder = decoder ?? defaultDecoder

return try decoder.decode(
ResponseModel.self,
from: data
)
}
}
6 changes: 6 additions & 0 deletions Sources/MicroClient/NetworkResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foundation

public struct NetworkResponse<T> {
public let value: T
public let response: URLResponse
}
1 change: 1 addition & 0 deletions Sources/MicroClient/Responses/VoidRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
public struct VoidRequest: Encodable { }
1 change: 1 addition & 0 deletions Sources/MicroClient/Responses/VoidResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
public struct VoidResponse: Decodable { }

0 comments on commit c7d75ae

Please sign in to comment.