67 lines
1.9 KiB
Swift
67 lines
1.9 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)
|
|
}
|
|
}
|
|
|
|
public class Networkservice {
|
|
public static let shared = Networkservice()
|
|
|
|
public init(){}
|
|
|
|
public func fetch<T: Decodable>(endpoint: String, type: T.Type) async throws -> T {
|
|
guard let url = URL(string: endpoint) else {
|
|
throw URLError(.badURL)
|
|
}
|
|
|
|
let (data, response) = try await URLSession.shared.data(from: url)
|
|
|
|
guard let httpResponse = response as? HTTPURLResponse,
|
|
200..<300 ~= httpResponse.statusCode else {
|
|
throw URLError(.badServerResponse)
|
|
}
|
|
|
|
return try JSONDecoder().decode(T.self, from: data)
|
|
}
|
|
}
|
|
|