Files
pos-system/apps/app-client-base-swift/AppClientBaseSwift/APIResponse.swift

128 lines
3.0 KiB
Swift

//
// APIResponse.swift
// AppClientBaseSwift
//
// API response wrapper models
// Các model wrapper cho API response
//
import Foundation
// MARK: - API Response Wrapper
// Wrapper Response API
/// Generic API response wrapper
/// Wrapper response API chung
struct APIResponse<T: Decodable>: Decodable {
/// Success status
/// Trng thái thành công
let success: Bool
/// Response data
/// D liu response
let data: T?
/// Error message if any
/// Thông báo li nếu có
let error: String?
/// Pagination info if any
/// Thông tin phân trang nếu có
let pagination: Pagination?
}
// MARK: - Pagination
// Phân trang
/// Pagination information
/// Thông tin phân trang
struct Pagination: Decodable {
let currentPage: Int?
let pageSize: Int?
let totalPages: Int?
let totalItems: Int?
enum CodingKeys: String, CodingKey {
case currentPage
case pageSize
case totalPages
case totalItems
}
}
// MARK: - Simple Response
// Response đơn gin
/// Simple success/error response
/// Response thành công/li đơn gin
struct SimpleResponse: Decodable {
let success: Bool
let message: String?
let error: String?
}
// MARK: - List Response
// Response danh sách
/// Generic list response wrapper
/// Wrapper response danh sách
struct ListResponse<T: Decodable>: Decodable {
let success: Bool
let data: [T]?
let error: String?
let pagination: Pagination?
}
// MARK: - APIResponse Extensions
// Extensions cho APIResponse
extension APIResponse {
/// Unwrap data or throw error
/// Unwrap data hoc throw error
/// - Returns: Unwrapped data / D liu đã unwrap
/// - Throws: APIError if not successful / APIError nếu không thành công
func unwrap() throws -> T {
guard success else {
throw APIError.serverError(
statusCode: 400,
message: error ?? "API request failed"
)
}
guard let data = data else {
throw APIError.noData
}
return data
}
/// Check if response is successful with data
/// Kim tra response có thành công và có data không
var isSuccessful: Bool {
success && data != nil
}
}
extension ListResponse {
/// Unwrap data or throw error
/// Unwrap data hoc throw error
/// - Returns: Unwrapped data array / Mng d liu đã unwrap
/// - Throws: APIError if not successful / APIError nếu không thành công
func unwrap() throws -> [T] {
guard success else {
throw APIError.serverError(
statusCode: 400,
message: error ?? "API request failed"
)
}
return data ?? []
}
/// Check if response is successful
/// Kim tra response có thành công không
var isSuccessful: Bool {
success
}
}