Skip to content

Commit

Permalink
Migrate to Swift Testing Framework and Code Cleanup (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
vamsii777 authored Nov 17, 2024
1 parent e11f8e2 commit d68b3cd
Show file tree
Hide file tree
Showing 12 changed files with 107 additions and 109 deletions.
24 changes: 11 additions & 13 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
// swift-tools-version: 5.8
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
Expand All @@ -12,7 +10,6 @@ let package = Package(
.watchOS(.v8),
],
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "JuspayKit",
targets: ["JuspayKit"]
Expand All @@ -24,24 +21,25 @@ let package = Package(
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(name: "JuspayKit", dependencies: [
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "Crypto", package: "swift-crypto"),
],
swiftSettings: swiftSettings),
.target(
name: "JuspayKit",
dependencies: [
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "Crypto", package: "swift-crypto"),
],
swiftSettings: swiftSettings
),
.testTarget(
name: "JuspayKitTests",
dependencies: ["JuspayKit"]
),
)
]
)

var swiftSettings: [SwiftSetting] {
var swiftSettings: [SwiftSetting] {
[
.enableUpcomingFeature("StrictConcurrency"),
.enableUpcomingFeature("ExistentialAny"),
.enableUpcomingFeature("FullTypedThrows"),
]
]
}
22 changes: 11 additions & 11 deletions Sources/JuspayKit/Core/APIHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public extension HTTPClientRequest.Body {
static func string(_ string: String) -> Self {
.bytes(.init(string: string))
}

/// Creates a request body from Data.
///
/// - Parameter data: The Data to be used as the request body.
Expand All @@ -37,7 +37,7 @@ public enum Environment: Sendable {
case production
/// The sandbox environment for testing.
case sandbox

/// The base URL for the selected environment.
var baseUrl: String {
switch self {
Expand All @@ -61,7 +61,7 @@ actor JuspayAPIHandler {
private let environment: Environment
/// JSON decoder for parsing API responses.
private let decoder = JSONDecoder()

/// Initializes a new instance of the JuspayAPIHandler.
///
/// - Parameters:
Expand All @@ -79,7 +79,7 @@ actor JuspayAPIHandler {
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase
}

/// Sends an API request to the Juspay service.
///
/// - Parameters:
Expand All @@ -105,29 +105,29 @@ actor JuspayAPIHandler {
]
let authString = "\(apiKey):".data(using: .utf8)!.base64EncodedString()
_headers.add(name: "Authorization", value: "Basic \(authString)")

headers.forEach { _headers.replaceOrAdd(name: $0.name, value: $0.value) }

var request = HTTPClientRequest(url: "\(baseURL)\(path)?\(query)")
request.headers = _headers
request.method = method
request.body = body

let response = try await httpClient.execute(request, timeout: .seconds(60))
let responseData = try await response.body.collect(upTo: .max)

// // Debug print the response data in human readable format
// if let responseString = responseData.getString(at: responseData.readerIndex, length: responseData.readableBytes) {
// print("Response Data: \(responseString)")
// } else {
// print("Failed to decode response data to string")
// }

guard response.status == .ok else {
let error = try self.decoder.decode(JuspayError.self, from: responseData)
let error = try decoder.decode(JuspayError.self, from: responseData)
throw error
}

return try decoder.decode(T.self, from: responseData)
}
}
15 changes: 7 additions & 8 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 @@ -80,15 +80,14 @@ public struct JuspayCustomerRoutes: CustomerRoutes {
"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)

}

/// 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 Down
11 changes: 5 additions & 6 deletions Sources/JuspayKit/HealthCheck/JuspayHealthStatus.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,19 @@ public struct Maintenance: Codable, Sendable {
public let url: String
}


public enum HealthStatus: String, Codable, Sendable {
case up = "UP"
case hasIssues = "HASISSUES"
case hasIssues = "HASISSUES"
case underMaintenance = "UNDERMAINTENANCE"
case identified = "IDENTIFIED"
case investigating = "INVESTIGATING"
case monitoring = "MONITORING"
case resolved = "RESOLVED"
case majorOutage = "MAJOROUTAGE"
case partialOutage = "PARTIALOUTAGE"
case minorOutage = "MINOROUTAGE"
case operational = "OPERATIONAL"
case partialOutage = "PARTIALOUTAGE"
case minorOutage = "MINOROUTAGE"
case operational = "OPERATIONAL"
case notStartedYet = "NOTSTARTEDYET"
case inProgress = "INPROGRESS"
case completed = "COMPLETED"
case completed = "COMPLETED"
}
13 changes: 6 additions & 7 deletions Sources/JuspayKit/Orders/OrderRoutes.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation
import NIO
import NIOHTTP1
import Foundation

/// A protocol defining the order-related API routes for the Juspay payment gateway.
///
Expand All @@ -14,7 +14,7 @@ public protocol OrderRoutes: JuspayAPIRoute {
///
/// - Throws: An error if the order retrieval fails or if there's a network issue.
func retrieve(orderId: String) async throws -> Order

/// Creates a new order in the Juspay system.
///
/// - Parameter parameters: A dictionary containing the necessary parameters for order creation.
Expand All @@ -30,17 +30,17 @@ public protocol OrderRoutes: JuspayAPIRoute {
public struct JuspayOrderRoutes: OrderRoutes {
/// 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 `JuspayOrderRoutes`.
///
/// - Parameter apiHandler: The `JuspayAPIHandler` instance to use for API requests.
init(apiHandler: JuspayAPIHandler) {
self.apiHandler = apiHandler
}

/// Retrieves an existing order from the Juspay system.
///
/// This method sends a GET request to the Juspay API to retrieve the order with the specified ID.
Expand All @@ -59,7 +59,7 @@ public struct JuspayOrderRoutes: OrderRoutes {
_headers.add(name: "version", value: formattedDate)
return try await apiHandler.send(method: .GET, path: "orders/\(orderId)", headers: _headers)
}

/// Creates a new order in the Juspay system.
///
/// This method sends a POST request to the Juspay API to create a new order with the provided parameters.
Expand All @@ -76,6 +76,5 @@ public struct JuspayOrderRoutes: OrderRoutes {
/// - `.serverError`: If the server encounters an error during order creation.
public func create(parameters: [String: Any]) async throws -> OrderCreationResponse {
return try await apiHandler.send(method: .POST, path: "orders", body: .string(parameters.percentEncoded()), headers: headers)

}
}
15 changes: 10 additions & 5 deletions Sources/JuspayKit/Refund/RefundItem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,21 @@ public struct RefundRequest: Codable, Sendable {
///
/// This identifier helps in tracking and referencing the specific refund request.
public let uniqueRequestId: String

/// The amount to be refunded.
///
/// This value should be a positive number representing the refund amount in the original transaction's currency.
public let amount: Double

private enum CodingKeys: String, CodingKey {
case uniqueRequestId = "unique_request_id"
case amount
}

public init(uniqueRequestId: String, amount: Double) {
self.uniqueRequestId = uniqueRequestId
self.amount = amount
}
}

/// A structure representing the response to a refund request in the Juspay system.
Expand Down Expand Up @@ -67,7 +72,7 @@ public struct RefundResponse: Codable, Sendable {
public let bankPg: String?
public let bankErrorMessage: String?
public let bankErrorCode: String?

public struct TransactionDetail: Codable, Sendable {
public let txnUuid: String?
public let txnId: String?
Expand All @@ -87,7 +92,7 @@ public struct RefundResponse: Codable, Sendable {
public let created: String?
public let statusId: Int?
}

public struct PaymentGatewayResponse: Codable, Sendable {
public let txnId: String?
public let rrn: String?
Expand All @@ -97,7 +102,7 @@ public struct RefundResponse: Codable, Sendable {
public let created: String?
public let authIdCode: String?
}

public struct CardDetails: Codable, Sendable {
public let usingToken: Bool?
public let usingSavedCard: Bool?
Expand Down
4 changes: 2 additions & 2 deletions Sources/JuspayKit/Session/SessionItem.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Foundation

public enum SessionAction: String, Codable, Sendable {
case paymentPage = "paymentPage"
case paymentManagement = "paymentManagement"
case paymentPage
case paymentManagement
}

public struct Session: Codable, Sendable {
Expand Down
10 changes: 5 additions & 5 deletions Sources/JuspayKit/Util/ErrorCode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ public enum ErrorCode: Error, Codable, Sendable, Equatable {
case accessDenied
case badRequest
case unknown(String)

public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
let rawValue = try container.decode(String.self)

switch rawValue {
case "duplicate.call":
self = .duplicateCall
Expand All @@ -36,7 +36,7 @@ public enum ErrorCode: Error, Codable, Sendable, Equatable {
self = .unknown(rawValue)
}
}

public init(rawValue: String) {
switch rawValue {
case "duplicate.call":
Expand All @@ -59,7 +59,7 @@ public enum ErrorCode: Error, Codable, Sendable, Equatable {
self = .unknown(rawValue)
}
}

public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
Expand All @@ -79,7 +79,7 @@ public enum ErrorCode: Error, Codable, Sendable, Equatable {
try container.encode("access_denied")
case .badRequest:
try container.encode("Bad request.")
case .unknown(let rawValue):
case let .unknown(rawValue):
try container.encode(rawValue)
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/JuspayKit/Util/JuspayError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public struct JuspayError: Error, Codable, Sendable {
public var statusId: Int?
/// Additional information about the error.
public var errorInfo: ErrorInfo?

public var localizedDescription: String {
return errorMessage ?? "Unknown error"
}
Expand Down
Loading

0 comments on commit d68b3cd

Please sign in to comment.