77 lines
2.5 KiB
Swift
77 lines
2.5 KiB
Swift
//
|
|
// EmployeeService.swift
|
|
// EmployeeDirectory
|
|
//
|
|
// Created by Matt Bruce on 3/3/25.
|
|
//
|
|
import Foundation
|
|
|
|
public class EmployeeService: EmployeeServiceProtocol {
|
|
// MARK: - Properties
|
|
public static let shared = EmployeeService() // Default shared instance
|
|
|
|
// MARK: - Initializer
|
|
|
|
public init() {}
|
|
|
|
// MARK: - Public Methods
|
|
|
|
/// This will get a list of all employees
|
|
/// - Returns: An Employees struct
|
|
public func getUsers(page: Int? = nil) async throws -> Employees {
|
|
var endpoint = "https://my.api.mockaroo.com/users.json?key=f298b840"
|
|
if let page {
|
|
endpoint += "&page=\(page)"
|
|
}
|
|
|
|
//ensure a valid URL
|
|
guard let url = URL(string: endpoint) else {
|
|
throw URLError(.badURL)
|
|
}
|
|
|
|
// Perform network request
|
|
let (data, response) = try await URLSession.shared.data(from: url)
|
|
|
|
// Validate HTTP response
|
|
guard let httpResponse = response as? HTTPURLResponse,
|
|
200..<300 ~= httpResponse.statusCode else {
|
|
throw URLError(.badServerResponse)
|
|
}
|
|
|
|
// Decode the response into the specified type
|
|
return try JSONDecoder().decode(Employees.self, from: data)
|
|
}
|
|
}
|
|
|
|
// Mock Service Implementation for testing & previews.
|
|
struct MockEmployeeService: EmployeeServiceProtocol {
|
|
static let sample = createUser(page: 1, index: 1)
|
|
|
|
static func createUser(page: Int?, index: Int) -> Employee {
|
|
Employee(
|
|
uuid: UUID(),
|
|
firstName: "First \(index + ((page ?? 1) - 1) * 20)",
|
|
lastName: "Last \(index + ((page ?? 1) - 1) * 20)",
|
|
phoneNumber: "555555\(1000 + index)",
|
|
emailAddress: "user\(index)@example.com",
|
|
biography: "Biography for employee \(index)",
|
|
photoURLSmall: "https://example.com/photo_small.jpg",
|
|
photoURLLarge: "https://example.com/photo_large.jpg"
|
|
)
|
|
}
|
|
func getUsers(page: Int?) async throws -> Employees {
|
|
// Simulate network delay.
|
|
try await Task.sleep(nanoseconds: 500_000_000)
|
|
|
|
// Create dummy data (20 employees per page).
|
|
let dummyEmployees: [Employee] = (0..<20).map { i in
|
|
Self.createUser(page: page, index: i)
|
|
}
|
|
|
|
// Simulate that there are more pages if page is less than 5.
|
|
let hasNext = (page ?? 1) < 5
|
|
|
|
return Employees(result: dummyEmployees, hasNextPage: hasNext)
|
|
}
|
|
}
|