replace fetchViewer call in extension with a verift token call for faster feedback

This commit is contained in:
Satindar Dhillon
2022-05-16 11:18:30 -07:00
parent 70f6ae5040
commit e53b295cb1
5 changed files with 51 additions and 5 deletions

View File

@ -79,12 +79,12 @@ final class ShareExtensionViewModel: ObservableObject {
}
.store(in: &subscriptions)
// Using viewerPublisher to get fast feedback for auth/network errors
// Check connection to get fast feedback for auth/network errors
Task {
do {
_ = try await services.dataService.fetchViewer()
} catch {
debugText = "saveArticleError: \(error)"
let hasConnectionAndValidToken = await services.dataService.hasConnectionAndValidToken()
if !hasConnectionAndValidToken {
debugText = "saveArticleError: No connection or invalid token."
status = .failed(error: .unknown(description: ""))
}
}

View File

@ -0,0 +1,14 @@
import Foundation
public struct AuthVerification: Decodable {
public let authStatus: AuthStatus
}
public enum AuthStatus: String, Decodable {
case authenticated = "AUTHENTICATED"
case unAuthenticated = "NOT_AUTHENTICATED"
public var isAuthenticated: Bool {
self == .authenticated
}
}

View File

@ -55,6 +55,10 @@ public final class DataService: ObservableObject {
}
}
public func hasConnectionAndValidToken() async -> Bool {
await networker.hasConnectionAndValidToken()
}
private func resetCoreData() {
let storeContainer =
persistentContainer.persistentStoreCoordinator

View File

@ -20,3 +20,28 @@ public final class Networker {
self.urlSession = urlSession
}
}
extension Networker {
/// Test if the user has a network connection and a valid auth token
/// - Returns: A `Bool` value
func hasConnectionAndValidToken() async -> Bool {
let urlRequest = URLRequest.create(
baseURL: appEnvironment.serverBaseURL,
urlPath: "/api/auth/verify",
requestMethod: .get,
includeAuthToken: false
)
let resource = ServerResource<AuthVerification>(
urlRequest: urlRequest,
decode: AuthVerification.decode
)
do {
let authVerification = try await urlSession.performReq(resource: resource)
return authVerification.authStatus.isAuthenticated
} catch {
return false
}
}
}

View File

@ -33,6 +33,9 @@ extension ServerResponse {
}
}
/// Empty struct to use when a successful network call does not include any JSON
struct EmptyResponse: Decodable {}
extension URLSession {
func performReq<ResponseModel>(
resource: ServerResource<ResponseModel>