ServerConfiguration.swift
1231 bytes
1import Foundation
2
3public struct ServerConfiguration: Sendable {
4 public let baseURL: URL
5 public let token: String
6
7 public init(serverURL: String, token: String) throws {
8 let trimmedServerURL = serverURL.trimmingCharacters(in: .whitespacesAndNewlines)
9
10 guard !trimmedServerURL.isEmpty,
11 let url = URL(string: trimmedServerURL),
12 url.scheme?.lowercased() == "https",
13 url.host != nil,
14 url.user == nil,
15 url.password == nil,
16 url.query == nil,
17 url.fragment == nil else {
18 throw ConfigurationError.invalidServerURL
19 }
20
21 guard !token.isEmpty else {
22 throw ConfigurationError.missingToken
23 }
24
25 baseURL = url
26 self.token = token
27 }
28
29 public func endpoint(path: String) -> URL {
30 baseURL.appendingPathComponent(path)
31 }
32}
33
34public enum ConfigurationError: LocalizedError {
35 case invalidServerURL
36 case missingToken
37
38 public var errorDescription: String? {
39 switch self {
40 case .invalidServerURL:
41 "Enter a valid HTTPS server URL."
42 case .missingToken:
43 "Enter the API token."
44 }
45 }
46}