Last active
February 1, 2023 16:12
-
-
Save temptempest/2ac849abbd75f824a46679754c48911d to your computer and use it in GitHub Desktop.
Assembled Endpoint for the Network layer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// Assembled Endpoint for the Network layer | |
| /// Usage: Endpoint(host: "https://www.host.com", path: "/path", method: .get) | |
| /// .addQuery(key: "queryKey", value: "queryValue") | |
| /// .addHeader(name: "headerKey", value: "headerValue") | |
| /// .addBody(name: "bodyKey", value: "bodyValue") | |
| /// .addBody(name: "bodyKey2", value: ["1","2","3"]) | |
| public struct Endpoint { | |
| public enum Method: String { | |
| case get = "GET" | |
| case post = "POST" | |
| case put = "PUT" | |
| case delete = "DELETE" | |
| case patch = "PATCH" | |
| } | |
| private let scheme: String | |
| private let host: String | |
| private let path: String | |
| private var queryItems: [URLQueryItem] = [] | |
| private var headers: [String: String] = [:] | |
| private var body: [String: Any] = [:] | |
| public let method: Method | |
| public var url: URL { | |
| var components = URLComponents() | |
| components.scheme = scheme | |
| components.path = path | |
| components.queryItems = queryItems | |
| return components.url! | |
| } | |
| public init(host: String, path: String, method: Method) { | |
| let hostArray = host.components(separatedBy: "://") | |
| self.scheme = hostArray[0] | |
| self.host = hostArray[1] | |
| self.path = path | |
| self.method = method | |
| } | |
| public func addQuery(key: String, value: String) -> Endpoint { | |
| var new = self | |
| let query = URLQueryItem(name: key, value: value) | |
| new.queryItems.append(query) | |
| return new | |
| } | |
| public func addHeader(name: String, value: String) -> Endpoint { | |
| var new = self | |
| new.headers[name] = value | |
| return new | |
| } | |
| public func addBody(name: String, value: [String]) -> Endpoint { | |
| var new = self | |
| new.body[name] = value | |
| return new | |
| } | |
| public func addBody(name: String, value: String) -> Endpoint { | |
| var new = self | |
| new.body[name] = value | |
| return new | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment