Skip to content

Commit

Permalink
Refactor: Error handling and base URL logic
Browse files Browse the repository at this point in the history
Centralized error handling logic and simplified base URL configuration, making the code more readable and maintainable.
  • Loading branch information
vamsii777 committed Oct 12, 2024
1 parent 4e60083 commit 7997863
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 47 deletions.
10 changes: 3 additions & 7 deletions Sources/JuspayKit/Core/APIHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ public enum Environment: Sendable {
var baseUrl: String {
switch self {
case .production:
APIBase
return APIBase
case .sandbox:
SandboxAPIBase
return SandboxAPIBase
}
}
}
Expand Down Expand Up @@ -98,11 +98,7 @@ actor JuspayAPIHandler {
body: HTTPClientRequest.Body = .bytes(.init(string: "")),
headers: HTTPHeaders
) async throws -> T {
var baseURL: String = if healthCheck == true {
HealthStatusAPIBase
} else {
environment.baseUrl
}
let baseURL: String = healthCheck == true ? HealthStatusAPIBase : environment.baseUrl
var _headers: HTTPHeaders = [
"x-merchantid": merchantId,
"Content-Type": "application/x-www-form-urlencoded",
Expand Down
53 changes: 31 additions & 22 deletions Sources/JuspayKit/Customer/CustomerRoutes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public protocol CustomerRoutes: JuspayAPIRoute {
///
/// - Throws: An error if the customer creation fails or if there's a network issue.
func create(objectReferenceId: String, mobileNumber: String, emailAddress: String, firstName: String, lastName: String, mobileCountryCode: String, getClientAuthToken: Bool) async throws -> Customer

/// Retrieves an existing customer from the Juspay system.
///
/// - Parameters:
Expand All @@ -44,17 +44,17 @@ public protocol CustomerRoutes: JuspayAPIRoute {
public struct JuspayCustomerRoutes: CustomerRoutes {
/// The HTTP headers to be sent with each request.
public var headers: HTTPHeaders = [:]

/// The API handler responsible for making network requests.
private let apiHandler: JuspayAPIHandler

/// Initializes a new instance of `JuspayCustomerRoutes`.
///
/// - Parameter apiHandler: The `JuspayAPIHandler` instance to use for API requests.
init(apiHandler: JuspayAPIHandler) {
self.apiHandler = apiHandler
}

/// Creates a new customer in the Juspay system.
///
/// This method sends a POST request to the Juspay API to create a new customer with the provided information.
Expand All @@ -72,22 +72,26 @@ public struct JuspayCustomerRoutes: CustomerRoutes {
///
/// - Throws: An error if the customer creation fails or if there's a network issue.
public func create(objectReferenceId: String, mobileNumber: String, emailAddress: String, firstName: String, lastName: String, mobileCountryCode: String, getClientAuthToken: Bool = false) async throws -> Customer {
var body = [
"object_reference_id": objectReferenceId,
"mobile_number": mobileNumber,
"email_address": emailAddress,
"first_name": firstName,
"last_name": lastName,
"mobile_country_code": mobileCountryCode,
]

if getClientAuthToken {
body["options.get_client_auth_token"] = "true"
do {
var body = [
"object_reference_id": objectReferenceId,
"mobile_number": mobileNumber,
"email_address": emailAddress,
"first_name": firstName,
"last_name": lastName,
"mobile_country_code": mobileCountryCode,
]

if getClientAuthToken {
body["options.get_client_auth_token"] = "true"
}

return try await apiHandler.send(method: .POST, path: "customers", body: .string(body.queryParameters), headers: headers)
} catch let error as JuspayError {
throw handleJuspayError(error)
}

return try await apiHandler.send(method: .POST, path: "customers", body: .string(body.queryParameters), headers: headers)
}

/// Retrieves an existing customer from the Juspay system.
///
/// This method sends a GET request to the Juspay API to retrieve the customer information for the specified customer ID.
Expand All @@ -100,10 +104,15 @@ public struct JuspayCustomerRoutes: CustomerRoutes {
///
/// - Throws: An error if the customer retrieval fails or if there's a network issue.
public func retrieve(customerId: String, getClientAuthToken: Bool = false) async throws -> Customer {
var query = ""
if getClientAuthToken {
query = "options.get_client_auth_token=true"
do {
var query = ""
if getClientAuthToken {
query = "options.get_client_auth_token=true"
}
return try await apiHandler.send(method: .GET, path: "customers/\(customerId)", query: query, headers: headers)

} catch let error as JuspayError {
throw handleJuspayError(error)
}
return try await apiHandler.send(method: .GET, path: "customers/\(customerId)", query: query, headers: headers)
}
}
16 changes: 12 additions & 4 deletions Sources/JuspayKit/HealthCheck/JuspayHealthRoutes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,17 @@ public struct JuspayHealthRoutes: HealthCheckRoutes {
/// - Returns: A `JuspayHealthStatus` indicating the current status of the Juspay API.
/// - Throws: An error if the health check request fails.
public func check() async throws -> JuspayHealthStatus {
try await apiHandler.send(
healthCheck: true,
method: .GET, path: "/summary.json", headers: headers
)
do {
return try await apiHandler.send(
healthCheck: true,
method: .GET, path: "/summary.json", headers: headers
)
} catch let error as JuspayError {
// Handle Juspay-specific errors
throw error
} catch {
// Handle other errors
throw error
}
}
}
15 changes: 1 addition & 14 deletions Sources/JuspayKit/Orders/OrderRoutes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,7 @@ public struct JuspayOrderRoutes: OrderRoutes {
do {
return try await apiHandler.send(method: .POST, path: "orders", body: .string(parameters.percentEncoded()), headers: headers)
} catch let error as JuspayError {
switch error {
case let .invalidInput(message):
throw JuspayError.orderCreationFailed(message: "Invalid input: \(message)")
case .authenticationFailed:
throw JuspayError.authenticationFailed
case let .serverError(message):
throw JuspayError.serverError(message: "Server error during order creation: \(message)")
case let .orderCreationFailed(message):
throw JuspayError.orderCreationFailed(message: message)
case let .refundCreationFailed(message: message):
throw JuspayError.refundCreationFailed(message: message)
case .invalidResponse:
throw JuspayError.invalidResponse
}
throw handleJuspayError(error)
}
}
}
17 changes: 17 additions & 0 deletions Sources/JuspayKit/Util/JuspayError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,20 @@ public enum JuspayError: Error, Codable, Sendable {
}
}
}

public func handleJuspayError(_ error: JuspayError) -> JuspayError {
switch error {
case let .invalidInput(message):
return .orderCreationFailed(message: "Invalid input: \(message)")
case .authenticationFailed:
return .authenticationFailed
case let .serverError(message):
return .serverError(message: "Server error during order creation: \(message)")
case let .orderCreationFailed(message):
return .orderCreationFailed(message: message)
case let .refundCreationFailed(message):
return .refundCreationFailed(message: message)
case .invalidResponse:
return .invalidResponse
}
}

0 comments on commit 7997863

Please sign in to comment.