From af3f658d99a30f5871bde1b9675daadbaee05971 Mon Sep 17 00:00:00 2001 From: Tony Bark <35226681+tonytins@users.noreply.github.com> Date: Sat, 22 Aug 2026 16:39:39 -0400 Subject: [PATCH] WIP http client Roughly based on the Amtraker node library so this and the models will eventually be spun off as one too --- Sources/AmtrakStatus/AmtrakClient.swift | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Sources/AmtrakStatus/AmtrakClient.swift diff --git a/Sources/AmtrakStatus/AmtrakClient.swift b/Sources/AmtrakStatus/AmtrakClient.swift new file mode 100644 index 0000000..ec60e44 --- /dev/null +++ b/Sources/AmtrakStatus/AmtrakClient.swift @@ -0,0 +1,34 @@ +import Foundation + +enum AmtrakError: Error { + case invalidURL(String) + case invalidResponse + case httpStatus(Int) + case stationNotFound(String) +} + +struct AmtrakClient { + var decoder = JSONDecoder() + + let stationBaseURL = "https://api.amtraker.com/v3/stations" + let trainsBaseURL = "https://api.amtraker.com/v3/trains" + let staleBaseURL = "https://api.amtraker.com/v3/stale" + + func get(_ urlString: String) async throws -> T { + + guard let url = URL(string: urlString) else { + throw AmtrakError.invalidURL(urlString) + } + + let (data, reponse) = try await URLSession.shared.data(from: url) + guard let http = reponse as? HTTPURLResponse else { + throw AmtrakError.invalidResponse + } + + guard (200..<300).contains(http.statusCode) else { + throw AmtrakError.httpStatus(http.statusCode) + } + + return try decoder.decode(T.self, from: data) + } +}