Files
pulse-mobile/PulseHealth/Services/APIService.swift

124 lines
5.5 KiB
Swift

import Foundation
enum APIError: Error, LocalizedError {
case unauthorized
case networkError(String)
case decodingError(String)
case serverError(Int, String)
var errorDescription: String? {
switch self {
case .unauthorized: return "Неверный email или пароль"
case .networkError(let msg): return "Ошибка сети: \(msg)"
case .decodingError(let msg): return "Ошибка данных: \(msg)"
case .serverError(let code, let msg): return "Ошибка сервера \(code): \(msg)"
}
}
}
class APIService {
static let shared = APIService()
let baseURL = "https://health.digital-home.site"
private func makeRequest(url: URL, method: String = "GET", token: String? = nil, body: Data? = nil) -> URLRequest {
var req = URLRequest(url: url)
req.httpMethod = method
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.timeoutInterval = 15
if let token = token {
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
req.httpBody = body
return req
}
func login(email: String, password: String) async throws -> LoginResponse {
let url = URL(string: "\(baseURL)/api/auth/login")!
let body = try JSONEncoder().encode(LoginRequest(email: email, password: password))
let req = makeRequest(url: url, method: "POST", body: body)
let (data, response) = try await URLSession.shared.data(for: req)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.networkError("Нет ответа от сервера")
}
if httpResponse.statusCode == 401 {
throw APIError.unauthorized
}
if httpResponse.statusCode != 200 {
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
throw APIError.serverError(httpResponse.statusCode, msg)
}
do {
return try JSONDecoder().decode(LoginResponse.self, from: data)
} catch {
throw APIError.decodingError(error.localizedDescription)
}
}
func register(email: String, password: String, name: String) async throws -> LoginResponse {
let url = URL(string: "\(baseURL)/api/auth/register")!
let body = try JSONEncoder().encode(["email": email, "password": password, "name": name])
let req = makeRequest(url: url, method: "POST", body: body)
let (data, response) = try await URLSession.shared.data(for: req)
guard let httpResponse = response as? HTTPURLResponse else { throw APIError.networkError("Нет ответа") }
if httpResponse.statusCode == 409 { throw APIError.serverError(409, "Email уже занят") }
if httpResponse.statusCode != 200 && httpResponse.statusCode != 201 {
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
throw APIError.serverError(httpResponse.statusCode, msg)
}
return try JSONDecoder().decode(LoginResponse.self, from: data)
}
func forgotPassword(email: String) async throws {
let url = URL(string: "\(baseURL)/api/auth/forgot-password")!
let body = try JSONEncoder().encode(["email": email])
let req = makeRequest(url: url, method: "POST", body: body)
_ = try await URLSession.shared.data(for: req)
}
func getProfile(token: String) async throws -> ProfileResponse {
let url = URL(string: "\(baseURL)/api/profile")!
let req = makeRequest(url: url, token: token)
let (data, _) = try await URLSession.shared.data(for: req)
return try JSONDecoder().decode(ProfileResponse.self, from: data)
}
func getReadiness(token: String) async throws -> ReadinessResponse {
let url = URL(string: "\(baseURL)/api/health/readiness")!
let req = makeRequest(url: url, token: token)
let (data, response) = try await URLSession.shared.data(for: req)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw APIError.networkError("Readiness недоступен")
}
return try JSONDecoder().decode(ReadinessResponse.self, from: data)
}
func getLatest(token: String) async throws -> LatestHealthResponse {
let url = URL(string: "\(baseURL)/api/health/latest")!
let req = makeRequest(url: url, token: token)
let (data, response) = try await URLSession.shared.data(for: req)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw APIError.networkError("Latest недоступен")
}
return try JSONDecoder().decode(LatestHealthResponse.self, from: data)
}
func getHeatmap(token: String, days: Int = 7) async throws -> [HeatmapEntry] {
let url = URL(string: "\(baseURL)/api/health/heatmap?days=\(days)")!
let req = makeRequest(url: url, token: token)
let (data, response) = try await URLSession.shared.data(for: req)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw APIError.networkError("Heatmap недоступен")
}
// Try array first, then wrapped response
if let entries = try? JSONDecoder().decode([HeatmapEntry].self, from: data) {
return entries
}
let wrapped = try JSONDecoder().decode(HeatmapResponse.self, from: data)
return wrapped.data
}
}