This commit is contained in:
Daniel Arantes Loverde
2026-02-06 09:51:53 -03:00
parent 379bb35cfa
commit 92c2a67736
13 changed files with 574 additions and 138 deletions

View File

@@ -1,5 +1,16 @@
import Foundation
enum ApiServiceError: Error, LocalizedError {
case sessionExpired(String?)
var errorDescription: String? {
switch self {
case .sessionExpired(let message):
return message ?? "Sessao expirada. Faca login novamente."
}
}
}
struct ApiEnvelope<T: Decodable>: Decodable {
let error: Bool
let code: String?
@@ -16,18 +27,30 @@ final class ApiService {
self.tokenStore = tokenStore
}
private func send<T: Decodable>(_ req: ApiRequest) async throws -> T {
do {
return try await client.send(req)
} catch let error as NetworkError {
if case .unauthorized(let message) = error {
tokenStore.clear()
throw ApiServiceError.sessionExpired(message)
}
throw error
}
}
// MARK: - Auth
func requestOtp(email: String) async throws -> ApiEnvelope<EmptyResult> {
let body = try JSONEncoder().encode(["email": email])
let req = ApiRequest(path: "/api/customer/login", method: "POST", module: .customer, requiresAuth: false, body: body)
return try await client.send(req)
return try await send(req)
}
func validateOtp(email: String, otp: String) async throws -> ApiEnvelope<LoginResult> {
let body = try JSONEncoder().encode(["email": email, "otp": otp])
let req = ApiRequest(path: "/api/customer/login", method: "POST", module: .customer, requiresAuth: false, body: body)
let response: ApiEnvelope<LoginResult> = try await client.send(req)
let response: ApiEnvelope<LoginResult> = try await send(req)
if let token = response.result?.token {
tokenStore.jwt = token
}
@@ -36,7 +59,7 @@ final class ApiService {
func profile() async throws -> ApiEnvelope<CustomerProfile> {
let req = ApiRequest(path: "/api/customer/profile", method: "GET", module: .customer, requiresAuth: true)
return try await client.send(req)
return try await send(req)
}
// MARK: - Stores
@@ -53,7 +76,7 @@ final class ApiService {
items.append(URLQueryItem(name: "search", value: search))
}
let req = ApiRequest(path: "/api/app/stores", method: "GET", module: .app, requiresAuth: true, queryItems: items)
return try await client.send(req)
return try await send(req)
}
}