Files
FrenoCorp/Lendair/Services/NotificationService.swift
Michael Freno bc7bf124f5 Fix P0-P3 code review issues for clubs and challenges (FRE-4664)
P0: Fix variable shadowing in ClubService.createClub/updateClub and
    ChallengeService.createChallenge/updateChallenge — renamed local
    'var request' to 'var urlRequest' so JSONEncoder encodes the
    typed parameter, not the URLRequest.

P1: Wire CreateClubSheet and CreateChallengeSheet to parent ViewModel —
    sheets now receive viewModel and call createClub/createChallenge
    before dismissing.

P2: Extract HTTPMethod enum to shared Utils/HTTPMethod.swift (was
    defined in NotificationService). Remove dead 'body' parameter from
    buildRequest in all three services. Add error alert UI to
    ClubsView and ChallengesView.

P3: Replace forced URL unwrap with static let defaultBaseURL in all
    three services. Fix MockChallengeService.updateChallenge to track
    updateCalled instead of always throwing notFound.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-05-10 06:42:00 -04:00

138 lines
4.8 KiB
Swift

import Foundation
// MARK: - Service Protocol
protocol NotificationsServiceProtocol: Sendable {
func list(params: NotificationListParams = NotificationListParams()) async throws -> [NotificationItem]
func markAsRead(id: String) async throws
func markAllAsRead() async throws
func getUnreadCount() async throws -> Int
}
// MARK: - Default Service
class NotificationsService: NotificationsServiceProtocol {
private let baseURL: URL
private let session: URLSession
private let authToken: String?
static let defaultBaseURL: URL = URL(string: "http://localhost:3000")!
init(
baseURL: URL = defaultBaseURL,
session: URLSession = .shared,
authToken: String? = nil
) {
self.baseURL = baseURL
self.session = session
self.authToken = authToken
}
func list(params: NotificationListParams = NotificationListParams()) async throws -> [NotificationItem] {
var components = URLComponents(url: baseURL.appendingPathComponent("/api/notifications"), resolvingAgainstBaseURL: true)!
var queryItems: [URLQueryItem] = [
URLQueryItem(name: "limit", value: String(params.limit)),
URLQueryItem(name: "offset", value: String(params.offset))
]
components.queryItems = queryItems
let request = try buildRequest(url: components.url!)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoded = try JSONDecoder().decode(NotificationListResponse.self, from: data)
return decoded.notifications
}
func markAsRead(id: String) async throws {
let url = baseURL.appendingPathComponent("/api/notifications/\(id)/read")
let request = try buildRequest(url: url, method: .patch)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
_ = try JSONDecoder().decode(NotificationMarkAsReadResponse.self, from: data)
}
func markAllAsRead() async throws {
let url = baseURL.appendingPathComponent("/api/notifications/read-all")
let request = try buildRequest(url: url, method: .patch)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
_ = try JSONDecoder().decode(NotificationMarkAllReadResponse.self, from: data)
}
func getUnreadCount() async throws -> Int {
let url = baseURL.appendingPathComponent("/api/notifications/unread-count")
let request = try buildRequest(url: url)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoded = try JSONDecoder().decode(NotificationUnreadCountResponse.self, from: data)
return decoded.count
}
// MARK: - Helpers
private func buildRequest(url: URL, method: HTTPMethod = .get) throws -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let token = authToken {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
return request
}
private func validateResponse(_ response: URLResponse) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw NotificationError.invalidResponse
}
guard (200...299).contains(httpResponse.statusCode) else {
switch httpResponse.statusCode {
case 401: throw NotificationError.unauthorized
case 403: throw NotificationError.forbidden
case 404: throw NotificationError.notFound
case 429: throw NotificationError.rateLimited
case 500...599: throw NotificationError.serverError(httpResponse.statusCode)
default: throw NotificationError.httpError(httpResponse.statusCode)
}
}
}
}
// MARK: - Error Types
enum NotificationError: LocalizedError {
case invalidResponse
case unauthorized
case forbidden
case notFound
case rateLimited
case serverError(Int)
case httpError(Int)
case decodingError(Error)
var errorDescription: String {
switch self {
case .invalidResponse: return "Invalid server response"
case .unauthorized: return "Unauthorized — please log in again"
case .forbidden: return "Forbidden — check permissions"
case .notFound: return "Notification not found"
case .rateLimited: return "Too many requests — try again shortly"
case .serverError(let code): return "Server error (\(code))"
case .httpError(let code): return "HTTP error (\(code))"
case .decodingError(let error): return "Decoding error: \(error.localizedDescription)"
}
}
}
// MARK: - HTTP Method (moved to Utils/HTTPMethod.swift)