Skip to content

Commit

Permalink
Rename and refactor internals
Browse files Browse the repository at this point in the history
  • Loading branch information
fpseverino committed Nov 15, 2024
1 parent f739d45 commit d154a94
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 39 deletions.
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ let package = Package(
.library(name: "AppleMapsKit", targets: ["AppleMapsKit"])
],
dependencies: [
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.0"),
.package(url: "https://github.com/vapor/jwt-kit.git", from: "5.0.1"),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.1"),
.package(url: "https://github.com/vapor/jwt-kit.git", from: "5.1.1"),
],
targets: [
.target(
Expand Down
48 changes: 24 additions & 24 deletions Sources/AppleMapsKit/AppleMapsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import NIOHTTP1
public struct AppleMapsClient: Sendable {
static let apiServer = "https://maps-api.apple.com"
private let httpClient: HTTPClient
private let authorizationProvider: AuthorizationProvider
private let authClient: AuthClient

private let decoder = JSONDecoder()

Expand All @@ -23,9 +23,8 @@ public struct AppleMapsClient: Sendable {
/// - key: A MapKit JS private key.
public init(httpClient: HTTPClient, teamID: String, keyID: String, key: String) {
self.httpClient = httpClient
self.authorizationProvider = AuthorizationProvider(
self.authClient = AuthClient(
httpClient: httpClient,
apiServer: Self.apiServer,
teamID: teamID,
keyID: keyID,
key: key
Expand Down Expand Up @@ -350,8 +349,7 @@ public struct AppleMapsClient: Sendable {
queries.append(URLQueryItem(name: "lang", value: lang))
}
if let requestsAlternateRoutes {
queries.append(
URLQueryItem(name: "requestsAlternateRoutes", value: "\(requestsAlternateRoutes)"))
queries.append(URLQueryItem(name: "requestsAlternateRoutes", value: "\(requestsAlternateRoutes)"))
}
if let searchLocation {
queries.append(URLQueryItem(name: "searchLocation", value: "\(searchLocation.latitude),\(searchLocation.longitude)"))
Expand Down Expand Up @@ -468,6 +466,24 @@ public struct AppleMapsClient: Sendable {
)
}

/// Converts an address to a coordinate.
///
/// - Parameter address: Address for which coordinate should be found.
///
/// - Throws: ``AppleMapsKitError/noPlacesFound`` if no places are found.
///
/// - Returns: A tuple representing coordinate.
private func getCoordinate(from address: String) async throws -> (latitude: Double, longitude: Double) {
let places = try await geocode(address: address)
guard let coordinate = places.first?.coordinate,
let latitude = coordinate.latitude,
let longitude = coordinate.longitude
else {
throw AppleMapsKitError.noPlacesFound
}
return (latitude, longitude)
}

/// Obtain a ``Place`` object for a given Place ID.
///
/// - Parameters:
Expand Down Expand Up @@ -510,7 +526,9 @@ public struct AppleMapsClient: Sendable {
url.append(queryItems: [URLQueryItem(name: "ids", value: ids.joined(separator: ","))])
return try await decoder.decode(AlternateIDsResponse.self, from: httpGet(url: url))
}
}

extension AppleMapsClient {
/// Makes an HTTP GET request.
///
/// - Parameter url: URL for the request.
Expand All @@ -520,7 +538,7 @@ public struct AppleMapsClient: Sendable {
/// - Throws: Error response object.
private func httpGet(url: URL) async throws -> ByteBuffer {
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "Bearer \(try await authorizationProvider.accessToken)")
headers.add(name: "Authorization", value: "Bearer \(try await authClient.accessToken)")

var request = HTTPClientRequest(url: url.absoluteString)
request.headers = headers
Expand All @@ -533,22 +551,4 @@ public struct AppleMapsClient: Sendable {
throw try await decoder.decode(ErrorResponse.self, from: response.body.collect(upTo: 1024 * 1024))
}
}

/// Converts an address to a coordinate.
///
/// - Parameter address: Address for which coordinate should be found.
///
/// - Throws: ``AppleMapsKitError/noPlacesFound`` if no places are found.
///
/// - Returns: A tuple representing coordinate.
private func getCoordinate(from address: String) async throws -> (latitude: Double, longitude: Double) {
let places = try await geocode(address: address)
guard let coordinate = places.first?.coordinate,
let latitude = coordinate.latitude,
let longitude = coordinate.longitude
else {
throw AppleMapsKitError.noPlacesFound
}
return (latitude, longitude)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// AuthorizationProvider.swift
// AuthClient.swift
// apple-maps-kit
//
// Created by FarouK on 11/10/2024.
Expand All @@ -10,19 +10,17 @@ import Foundation
import JWTKit
import NIOHTTP1

actor AuthorizationProvider {
actor AuthClient {
private let httpClient: HTTPClient
private let apiServer: String
private let teamID: String
private let keyID: String
private let key: String

private var currentToken: TokenResponse?
private var refreshTask: Task<TokenResponse, any Error>?

init(httpClient: HTTPClient, apiServer: String, teamID: String, keyID: String, key: String) {
init(httpClient: HTTPClient, teamID: String, keyID: String, key: String) {
self.httpClient = httpClient
self.apiServer = apiServer
self.teamID = teamID
self.keyID = keyID
self.key = key
Expand Down Expand Up @@ -70,13 +68,13 @@ actor AuthorizationProvider {
}
}

extension AuthorizationProvider {
extension AuthClient {
private var tokenResponse: TokenResponse {
get async throws {
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "Bearer \(try await jwtToken)")

var request = HTTPClientRequest(url: "\(apiServer)/v1/token")
var request = HTTPClientRequest(url: "\(AppleMapsClient.apiServer)/v1/token")
request.headers = headers

let response = try await httpClient.execute(request, timeout: .seconds(30))
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/DTOs/ErrorResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public struct ErrorResponse: Error, Codable, Sendable {

extension ErrorResponse: CustomStringConvertible {
public var description: String {
var result = #"AppleMapsKitError(message: \#(message ?? "nil")"#
var result = #"AppleMapsError(message: \#(message ?? "nil")"#

if let details {
result.append(", details: \(details)")
Expand Down
2 changes: 1 addition & 1 deletion Tests/AppleMapsKitTests/AppleMapsKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,6 @@ struct AppleMapsKitTests {

@Test("ErrorResponse.description") func errorResponseDescription() {
let errorResponse = ErrorResponse(details: ["detail1", "detail2"], message: "message")
#expect(errorResponse.description == #"AppleMapsKitError(message: message, details: ["detail1", "detail2"])"#)
#expect(errorResponse.description == #"AppleMapsError(message: message, details: ["detail1", "detail2"])"#)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// AuthorizationProviderTests.swift
// AuthTests.swift
// apple-maps-kit
//
// Created by FarouK on 12/10/2024.
Expand All @@ -10,9 +10,9 @@ import Testing

@testable import AppleMapsKit

@Suite("Authorization Tests")
struct AuthorizationTests {
// It's actually 1 second due to the expiration buffer on the token.
@Suite("Auth Tests")
struct AuthTests {
// The expiration time is actually 1 second, due to the expiration buffer on the token.
let token = TokenResponse(accessToken: "test", expiresInSeconds: 11)

@Test("Invalid Access Token") func invalidToken() async throws {
Expand Down

0 comments on commit d154a94

Please sign in to comment.