mirror of
https://github.com/tonytins/amtkstat.git
synced 2026-10-24 05:32:54 -04:00
WIP http client
Roughly based on the Amtraker node library so this and the models will eventually be spun off as one too
This commit is contained in:
parent
474bca2cc2
commit
af3f658d99
1 changed files with 34 additions and 0 deletions
34
Sources/AmtrakStatus/AmtrakClient.swift
Normal file
34
Sources/AmtrakStatus/AmtrakClient.swift
Normal file
|
|
@ -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<T: Decodable>(_ 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue