Refactor project structure and API
This commit is contained in:
66
Model/API/BaseAPI.swift
Normal file
66
Model/API/BaseAPI.swift
Normal file
@@ -0,0 +1,66 @@
|
||||
//
|
||||
// BaseAPI.swift
|
||||
// iKeyMon
|
||||
//
|
||||
// Created by tracer on 13.11.25.
|
||||
//
|
||||
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol ServerAPIProtocol {
|
||||
associatedtype LoadType: Codable
|
||||
associatedtype MemoryType: Codable
|
||||
associatedtype UtilizationType: Codable
|
||||
|
||||
func fetchSystemInfo() async throws -> SystemInfo
|
||||
func fetchLoad() async throws -> LoadType
|
||||
func fetchMemory() async throws -> MemoryType
|
||||
func fetchUtilization() async throws -> UtilizationType
|
||||
}
|
||||
|
||||
struct SystemInfo: Codable {
|
||||
let version: String
|
||||
let timestamp: Date
|
||||
let hostname: String
|
||||
}
|
||||
|
||||
class BaseAPIClient {
|
||||
let baseURL: URL
|
||||
let session: URLSession
|
||||
|
||||
init(baseURL: URL, session: URLSession = .shared) {
|
||||
self.baseURL = baseURL
|
||||
self.session = session
|
||||
}
|
||||
|
||||
func performRequest<T: Codable>(_ request: URLRequest, responseType: T.Type) async throws -> T {
|
||||
let (data, response) = try await session.data(for: request)
|
||||
|
||||
guard let httpResponse = response as? HTTPURLResponse else {
|
||||
throw APIError.invalidResponse
|
||||
}
|
||||
|
||||
guard 200...299 ~= httpResponse.statusCode else {
|
||||
throw APIError.httpError(httpResponse.statusCode)
|
||||
}
|
||||
|
||||
return try JSONDecoder().decode(T.self, from: data)
|
||||
}
|
||||
}
|
||||
|
||||
enum APIError: Error, LocalizedError {
|
||||
case invalidURL
|
||||
case invalidResponse
|
||||
case httpError(Int)
|
||||
case decodingError(Error)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL: return "Invalid URL"
|
||||
case .invalidResponse: return "Invalid response"
|
||||
case .httpError(let code): return "HTTP Error: \(code)"
|
||||
case .decodingError(let error): return "Decoding error: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user