Skip to content

Commit

Permalink
refactor: event strings to struct and object
Browse files Browse the repository at this point in the history
  • Loading branch information
hyochan committed Jul 26, 2024
1 parent 2841625 commit 8ac4b83
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 23 deletions.
17 changes: 11 additions & 6 deletions android/src/main/java/expo/modules/iap/ExpoIapModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ class ExpoIapModule :
const val EMPTY_SKU_LIST = "EMPTY_SKU_LIST"
}

object IapEvent {
const val PURCHASE_UPDATED = "purchase-updated"
const val PURCHASE_ERROR = "purchase-error"
}

private var billingClientCache: BillingClient? = null
private val skus: MutableMap<String, ProductDetails> = mutableMapOf()
private val context: Context
Expand All @@ -57,7 +62,7 @@ class ExpoIapModule :
val errorData = PlayUtils.getBillingResponseData(responseCode)
error["code"] = errorData.code
error["message"] = errorData.message
sendEvent("purchase-error", error)
sendEvent(IapEvent.PURCHASE_ERROR, error.toMap())
return
}

Expand Down Expand Up @@ -85,7 +90,7 @@ class ExpoIapModule :
item["obfuscatedProfileIdAndroid"] = accountIdentifiers.obfuscatedProfileId
}
promiseItems.add(item.toMap())
sendEvent("purchase-updated", item)
sendEvent(IapEvent.PURCHASE_UPDATED, item.toMap())
}
} else {
val result =
Expand All @@ -95,7 +100,7 @@ class ExpoIapModule :
"extraMessage" to
"The purchases are null. This is a normal behavior if you have requested DEFERRED proration. If not please report an issue.",
)
sendEvent("purchase-updated", result)
sendEvent(IapEvent.PURCHASE_UPDATED, result.toMap())
}
}

Expand All @@ -105,7 +110,7 @@ class ExpoIapModule :

Constants("PI" to Math.PI)

Events("purchase-error", "purchase-updated")
Events(IapEvent.PURCHASE_UPDATED, IapEvent.PURCHASE_ERROR)

AsyncFunction("initConnection") { promise: Promise ->
initBillingClient(promise) { promise.resolve(true) }
Expand Down Expand Up @@ -303,7 +308,7 @@ class ExpoIapModule :
val debugMessage =
"The number of skus (${skuArr.size}) must match: the number of offerTokens (${offerTokenArr.size}) for Subscriptions"
sendEvent(
"purchase-error",
IapEvent.PURCHASE_ERROR,
mapOf(
"debugMessage" to debugMessage,
"code" to "E_SKU_OFFER_MISMATCH",
Expand All @@ -320,7 +325,7 @@ class ExpoIapModule :
val debugMessage =
"The sku was not found. Please fetch products first by calling getItems"
sendEvent(
"purchase-error",
IapEvent.PURCHASE_ERROR,
mapOf(
"debugMessage" to debugMessage,
"code" to "E_SKU_NOT_FOUND",
Expand Down
28 changes: 15 additions & 13 deletions ios/ExpoIapModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ func serializeDebug (_ s: String) -> String? {
#endif
}

struct IapEvent {
static let PurchaseUpdated = "purchase-updated"
static let PurchaseError = "purchase-error"
static let TransactionIapUpdated = "iap-transaction-updated"
}

@available(iOS 15.0, *)
func serializeProduct(_ p: Product) -> [String: Any?] {
return [
Expand Down Expand Up @@ -81,7 +87,7 @@ func serialize(_ transaction: Transaction, _ result: VerificationResult<Transact
}

@available(iOS 15.0, *)
public class ExpoIapModule: Module, EXEventEmitter {
public class ExpoIapModule: Module {
private var transactions: [String: Transaction] = [:]
private var productStore: ProductStore?
private var hasListeners = false
Expand All @@ -94,7 +100,7 @@ public class ExpoIapModule: Module, EXEventEmitter {
"PI": Double.pi
])

Events("purchase-updated", "purchase-error", "iap-transaction-updated")
Events(IapEvent.PurchaseUpdated, IapEvent.PurchaseError, IapEvent.TransactionIapUpdated)

OnStartObserving {
hasListeners = true
Expand Down Expand Up @@ -154,13 +160,13 @@ public class ExpoIapModule: Module, EXEventEmitter {
func addTransaction(transaction: Transaction) {
purchasedItems.append(transaction)
if alsoPublishToEventListener {
self.sendEvent("purchase-updated", serializeTransaction(transaction))
self.sendEvent(IapEvent.PurchaseUpdated, serializeTransaction(transaction))
}
}

func addError(error: Error, errorDict: [String: String]) {
if alsoPublishToEventListener {
self.sendEvent("purchase-error", errorDict)
self.sendEvent(IapEvent.PurchaseError, errorDict)
}
}

Expand Down Expand Up @@ -248,7 +254,7 @@ public class ExpoIapModule: Module, EXEventEmitter {
return nil
} else {
self.transactions[String(transaction.id)] = transaction
self.sendEvent("purchase-updated", serializeTransaction(transaction))
self.sendEvent(IapEvent.PurchaseUpdated, serializeTransaction(transaction))
return serializeTransaction(transaction)
}

Expand Down Expand Up @@ -445,8 +451,8 @@ public class ExpoIapModule: Module, EXEventEmitter {
let transaction = try self.checkVerified(result)
self.transactions[String(transaction.id)] = transaction
if self.hasListeners {
self.sendEvent("purchase-updated", serializeTransaction(transaction))
self.sendEvent("iap-transaction-updated", ["transaction": serializeTransaction(transaction)])
self.sendEvent(IapEvent.PurchaseUpdated, serializeTransaction(transaction))
self.sendEvent(IapEvent.TransactionIapUpdated, ["transaction": serializeTransaction(transaction)])
}
} catch {
if self.hasListeners {
Expand All @@ -456,8 +462,8 @@ public class ExpoIapModule: Module, EXEventEmitter {
"code": IapErrors.E_TRANSACTION_VALIDATION_FAILED.rawValue,
"message": error.localizedDescription
]
self.sendEvent("purchase-error", err)
self.sendEvent("iap-transaction-updated", ["error": err])
self.sendEvent(IapEvent.PurchaseError, err)
self.sendEvent(IapEvent.TransactionIapUpdated, ["error": err])
}
}
}
Expand All @@ -474,10 +480,6 @@ public class ExpoIapModule: Module, EXEventEmitter {
removeTransactionObserver()
}

public func supportedEvents() -> [String] {
return ["purchase-updated", "purchase-error", "iap-transaction-updated"]
}

private func currentWindowScene() async -> UIWindowScene? {
await MainActor.run {
return UIApplication.shared.connectedScenes.first as? UIWindowScene
Expand Down
13 changes: 11 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export * from './modules/ios';
// Get the native constant value.
export const PI = ExpoIapModule.PI;

export enum IapEvent {
PurchaseUpdated = 'purchase-updated',
PurchaseError = 'purchase-error',
TransactionIapUpdated = 'iap-transaction-updated',
}

export async function setValueAsync(value: string) {
return await ExpoIapModule.setValueAsync(value);
}
Expand All @@ -42,14 +48,17 @@ export const emitter = new EventEmitter(
export const purchaseUpdatedListener = (
listener: (event: Purchase) => void,
) => {
const emitterSubscription = emitter.addListener('purchase-updated', listener);
const emitterSubscription = emitter.addListener(
IapEvent.PurchaseUpdated,
listener,
);
return emitterSubscription;
};

export const purchaseErrorListener = (
listener: (error: PurchaseError) => void,
) => {
return emitter.addListener<PurchaseError>('purchase-error', listener);
return emitter.addListener<PurchaseError>(IapEvent.PurchaseError, listener);
};

export function initConnection() {
Expand Down
4 changes: 2 additions & 2 deletions src/modules/ios.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Platform} from 'react-native';
import {emitter} from '..';
import {emitter, IapEvent} from '..';
import {Product, PurchaseError} from '../ExpoIap.types';
import type {
ProductIos,
Expand All @@ -21,7 +21,7 @@ export const transactionUpdatedIos = (
throw new Error('This method is only available on iOS');
}

return emitter.addListener('iap-transaction-updated', listener);
return emitter.addListener(IapEvent.TransactionIapUpdated, listener);
};

// Functions
Expand Down

0 comments on commit 8ac4b83

Please sign in to comment.