Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import ShopifyCheckoutSheetKit

/// A lightweight GraphQL client for the Storefront API without external dependencies
@available(iOS 16.0, *)
class GraphQLClient {
class GraphQLClient: Loggable {
let url: URL
private let headers: [String: String]
private let session: URLSession
Expand Down Expand Up @@ -78,10 +78,12 @@ class GraphQLClient {
let (data, response) = try await session.data(for: urlRequest)

guard let httpResponse = response as? HTTPURLResponse else {
logError("Could not decode response into expected: HTTPURLResponse")
throw GraphQLError.networkError("Invalid response")
}

if httpResponse.statusCode != 200 {
logError("Expected statusCode: 200, received: \(httpResponse.statusCode)")
throw GraphQLError.httpError(statusCode: httpResponse.statusCode, data: data)
}

Expand All @@ -91,6 +93,7 @@ class GraphQLClient {
let decodedResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)

if let errors = decodedResponse.errors, !errors.isEmpty {
logError("Reponse contained \(errors.count) error(s)")
throw GraphQLError.graphQLErrors(errors)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import Foundation

/// High-level API for Storefront operations using the custom GraphQL client
@available(iOS 16.0, *)
class StorefrontAPI: ObservableObject, StorefrontAPIProtocol {
class StorefrontAPI: ObservableObject, StorefrontAPIProtocol, Loggable {
let client: GraphQLClient

/// Initialize the Storefront API
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
MIT License

Copyright 2023 - Present, Shopify Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import Foundation
import ShopifyCheckoutSheetKit

/// Protocol for components that need logging with automatic namespace detection
@available(iOS 16.0, *)
internal protocol Loggable {
// var osLogger: OSLogger { get set }
}

/// Default implementation for Loggable protocol
@available(iOS 16.0, *)
extension Loggable {
internal var osLogger: OSLogger {
ShopifyAcceleratedCheckouts.logger.osLogger
}

/// Returns the name of the conforming class
///
/// Usage:
/// ```swift
/// class MyClass : Loggable {
/// func foo() {
/// print(namespace) // prints: 'MyClass'
/// }
/// }
/// ```
internal var namespace: String {
String(describing: type(of: self))
}

internal func createLogLine(
_ message: String,
method: String,
fileID: String,
line: Int
) -> String {
let fileName = fileID.split(separator: "/").last.map { String($0) } ?? fileID
return "[\(fileName):\(method):\(line)] \(message)"
}

/// Log a debug message with automatic namespace
internal func logDebug(
_ message: String,
method: String = #function,
fileID: String = #fileID,
line: Int = #line
) {
osLogger.debug(
createLogLine(message, method: method, fileID: fileID, line: line)
)
}

/// Log an info message with automatic namespace
internal func logInfo(
_ message: String,
method: String = #function,
fileID: String = #fileID,
line: Int = #line
) {
osLogger.info(
createLogLine(message, method: method, fileID: fileID, line: line)
)
}

/// Log an error message with automatic namespace
internal func logError(
_ message: String,
method: String = #function,
fileID: String = #fileID,
line: Int = #line
) {
osLogger.error(
createLogLine(message, method: method, fileID: fileID, line: line)
)
}

/// Log a fault message with automatic namespace
internal func logFault(
_ message: String,
method: String = #function,
fileID: String = #fileID,
line: Int = #line
) {
osLogger.fault(
createLogLine(message, method: method, fileID: fileID, line: line)
)
}
}

@available(iOS 16.0, *)
internal class Logger: Loggable {
var osLogger: ShopifyCheckoutSheetKit.OSLogger

init(prefix: String, logLevel: LogLevel) {
osLogger = OSLogger(prefix: prefix, logLevel: logLevel)
}

func setLogLevel(to logLevel: LogLevel) {
osLogger.logLevel = logLevel
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import Foundation

@available(iOS 16.0, *)
extension ShopifyAcceleratedCheckouts {
enum Error: LocalizedError {
case invariant(expected: String)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import ShopifyCheckoutSheetKit

@available(iOS 16.0, *)
public enum ShopifyAcceleratedCheckouts {
/// Storefront API version used for cart operations
/// Note: We also use `2025-07` for `cartRemovePersonalData` mutations. We are working towards migrating all requests to `2025-07`.
Expand All @@ -34,11 +35,14 @@ public enum ShopifyAcceleratedCheckouts {
/// Default: .error - which will emit "error" and "fault" logs
public static var logLevel: LogLevel = .error {
didSet {
logger.logLevel = logLevel
logger.setLogLevel(to: logLevel)
}
}

/// Shared logger for ShopifyAcceleratedCheckouts
/// To modify the logLevel
internal static var logger = OSLogger(prefix: name, logLevel: logLevel)
/// Use ShopifyAcceleratedCheckouts.logLevel to modify verbosity
internal static var logger = Logger(
prefix: name,
logLevel: logLevel
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ public struct AcceleratedCheckoutButtons: View {
public init(cartID: String) {
identifier = .cart(cartID: cartID).parse()
if case let .invariant(reason) = identifier {
ShopifyAcceleratedCheckouts.logger.error(reason)
ShopifyAcceleratedCheckouts.logger.logError(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't conform the Structs to Loggable so also using global here

"\(AcceleratedCheckoutButtons.self) failed to parse identifier: \(reason)"
)
_currentRenderState = State(initialValue: .error(reason: reason))
}
}
Expand All @@ -78,8 +80,10 @@ public struct AcceleratedCheckoutButtons: View {
public init(variantID: String, quantity: Int) {
identifier = .variant(variantID: variantID, quantity: quantity).parse()
if case let .invariant(reason) = identifier {
ShopifyAcceleratedCheckouts.logger.logError(
"\(AcceleratedCheckoutButtons.self) failed to parse identifier: \(reason)"
)
_currentRenderState = State(initialValue: .error(reason: reason))
ShopifyAcceleratedCheckouts.logger.error(reason)
}
}

Expand Down Expand Up @@ -127,7 +131,7 @@ public struct AcceleratedCheckoutButtons: View {
currentRenderState = .rendered
} catch {
let reason = "Error loading shop settings: \(error)"
ShopifyAcceleratedCheckouts.logger.error(reason)
ShopifyAcceleratedCheckouts.logger.logError(reason)
currentRenderState = .error(reason: reason)
}
}
Expand Down
Loading
Loading