This PR constains the work done to define the necessary protocols and enumerations to start defining remote API service as well as an implementation of the `URLProtocol` to mock requests and responses when using the `URLSession` to make remote calls. To provide further details about this work: - [x] declared the `Communications` library in the `Package` file; - [x] defined the minimum Apple platform versions in the `Package` file to support the async/await feature; - [x] defined the `HTTPRequestMethod` and `HTTPResponseCode` public enumerations; - [x] defined the `Endpoint` and `Client` public protocols; - [x] implemented the internal `MakeURLRequestUseCase` use case; - [x] implemented the `MockURLProtocol` class that mocks requests and responses on `URLSession` instances; - [x] started writing and updating the `README` file. Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Reviewed-on: #4
55 lines
1.5 KiB
Swift
55 lines
1.5 KiB
Swift
//
|
|
// MakeURLRequestUseCase.swift
|
|
// APICore
|
|
//
|
|
// Created by Javier Cicchelli on 10/04/2023.
|
|
// Copyright © 2023 Röck+Cöde. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
/// This use case generate a url request out of a given endpoint.
|
|
public struct MakeURLRequestUseCase {
|
|
|
|
// MARK: Initialisers
|
|
|
|
public init() {}
|
|
|
|
// MARK: Functions
|
|
|
|
/// Generate a `URLRequest` instance out of a given endpoint that conforms to the `Endpoint` protocol.
|
|
/// - Parameter endpoint: An endpoint which is used to generate a `URLRequest` instance from.
|
|
/// - Returns: A `URLRequest` instance filled with data provided by the given endpoint.
|
|
public func callAsFunction(endpoint: some Endpoint) throws -> URLRequest {
|
|
var urlComponents = URLComponents()
|
|
|
|
urlComponents.scheme = endpoint.scheme
|
|
urlComponents.host = endpoint.host
|
|
urlComponents.path = endpoint.path
|
|
|
|
if let port = endpoint.port {
|
|
urlComponents.port = port
|
|
}
|
|
|
|
guard let url = urlComponents.url else {
|
|
throw MakeURLRequestError.urlNotCreated
|
|
}
|
|
|
|
var urlRequest = URLRequest(url: url)
|
|
|
|
urlRequest.httpMethod = endpoint.method.rawValue
|
|
urlRequest.httpBody = endpoint.body
|
|
urlRequest.allHTTPHeaderFields = endpoint.headers
|
|
|
|
return urlRequest
|
|
}
|
|
|
|
}
|
|
|
|
// MARK: - Errors
|
|
|
|
enum MakeURLRequestError: Error {
|
|
case urlNotCreated
|
|
}
|
|
|