Skip to content

Commit

Permalink
refactor: async await refactoring - 1 (#768)
Browse files Browse the repository at this point in the history
Co-authored-by: Shiva Nandan <[email protected]>
  • Loading branch information
PritishBudhiraja and seekshiva authored Nov 12, 2024
1 parent 13f3c7e commit 68a1e15
Show file tree
Hide file tree
Showing 6 changed files with 183 additions and 207 deletions.
2 changes: 1 addition & 1 deletion src/Components/SavedMethodItem.res
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ let make = (~brandIcon, ~paymentItem: PaymentType.customerMethods, ~handleDelete
name="delete"
style={color: themeObj.colorDanger}
className="cursor-pointer ml-4 mb-[6px]"
onClick={_ => paymentItem->handleDelete}
onClick={_ => handleDelete(paymentItem)->ignore}
/>
</div>
<div className="w-full">
Expand Down
50 changes: 21 additions & 29 deletions src/Components/SavedPaymentManagement.res
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,31 @@
let make = (~savedMethods: array<PaymentType.customerMethods>, ~setSavedMethods) => {
open CardUtils
open Utils
open RecoilAtoms

let {iframeId} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys)
let {config} = Recoil.useRecoilValueFromAtom(RecoilAtoms.configAtom)
let customPodUri = Recoil.useRecoilValueFromAtom(RecoilAtoms.customPodUri)
let logger = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom)
let {iframeId} = Recoil.useRecoilValueFromAtom(keys)
let {config} = Recoil.useRecoilValueFromAtom(configAtom)
let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri)
let logger = Recoil.useRecoilValueFromAtom(loggerAtom)

let removeSavedMethod = (
savedMethods: array<PaymentType.customerMethods>,
paymentMethodId,
) => {
savedMethods->Array.filter(savedMethod => {
savedMethod.paymentMethodId !== paymentMethodId
})
}
let removeSavedMethod = (savedMethods: array<PaymentType.customerMethods>, paymentMethodId) =>
savedMethods->Array.filter(savedMethod => savedMethod.paymentMethodId !== paymentMethodId)

let handleDelete = (paymentItem: PaymentType.customerMethods) => {
let handleDelete = async (paymentItem: PaymentType.customerMethods) => {
messageParentWindow([
("fullscreen", true->JSON.Encode.bool),
("param", "paymentloader"->JSON.Encode.string),
("iframeId", iframeId->JSON.Encode.string),
])
open Promise
PaymentHelpers.deletePaymentMethod(
~ephemeralKey=config.ephemeralKey,
~paymentMethodId=paymentItem.paymentMethodId,
~logger,
~customPodUri,
)
->then(res => {

try {
let res = await PaymentHelpers.deletePaymentMethod(
~ephemeralKey=config.ephemeralKey,
~paymentMethodId=paymentItem.paymentMethodId,
~logger,
~customPodUri,
)

let dict = res->getDictFromJson
let paymentMethodId = dict->getString("payment_method_id", "")
let isDeleted = dict->getBool("deleted", false)
Expand All @@ -44,19 +40,15 @@ let make = (~savedMethods: array<PaymentType.customerMethods>, ~setSavedMethods)
} else {
logger.setLogError(~value=res->JSON.stringify, ~eventName=DELETE_SAVED_PAYMENT_METHOD)
}
messageParentWindow([("fullscreen", false->JSON.Encode.bool)])
resolve()
})
->catch(err => {
} catch {
| err =>
let exceptionMessage = err->formatException->JSON.stringify
logger.setLogError(
~value=`Error Deleting Saved Payment Method: ${exceptionMessage}`,
~eventName=DELETE_SAVED_PAYMENT_METHOD,
)
messageParentWindow([("fullscreen", false->JSON.Encode.bool)])
resolve()
})
->ignore
}
messageParentWindow([("fullscreen", false->JSON.Encode.bool)])
}

savedMethods
Expand Down
56 changes: 25 additions & 31 deletions src/Payments/PazeButton.res
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,40 @@ let make = (~token: SessionsType.token) => {
let {iframeId, publishableKey, clientSecret} = Recoil.useRecoilValueFromAtom(keys)
let {themeObj} = Recoil.useRecoilValueFromAtom(configAtom)
let options = Recoil.useRecoilValueFromAtom(optionAtom)
let (showLoader, setShowLoader) = React.useState(() => false)
let setIsShowOrPayUsing = Recoil.useSetRecoilState(RecoilAtoms.isShowOrPayUsing)
let setIsShowOrPayUsing = Recoil.useSetRecoilState(isShowOrPayUsing)
let loggerState = Recoil.useRecoilValueFromAtom(loggerAtom)
let intent = PaymentHelpers.usePaymentIntent(Some(loggerState), Paze)
let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(isManualRetryEnabled)
let intent = PaymentHelpers.usePaymentIntent(Some(loggerState), Paze)
let paymentIntentID = clientSecret->Option.getOr("")->getPaymentId

React.useEffect0(() => {
setIsShowOrPayUsing(_ => true)
None
})

let (showLoader, setShowLoader) = React.useState(() => false)
let onClick = _ => {
setShowLoader(_ => true)
let metadata =
[
("wallet", (token.walletName :> string)->JSON.Encode.string),
("clientId", token.clientId->JSON.Encode.string),
("clientName", token.clientName->JSON.Encode.string),
("clientProfileId", token.clientProfileId->JSON.Encode.string),
("sessionId", paymentIntentID->JSON.Encode.string),
("publishableKey", publishableKey->JSON.Encode.string),
("emailAddress", token.email_address->JSON.Encode.string),
("transactionAmount", token.transaction_amount->JSON.Encode.string),
("transactionCurrencyCode", token.transaction_currency_code->JSON.Encode.string),
]->getJsonFromArrayOfJson

messageParentWindow([
("fullscreen", true->JSON.Encode.bool),
("param", "pazeWallet"->JSON.Encode.string),
("iframeId", iframeId->JSON.Encode.string),
(
"metadata",
[
("wallet", (token.walletName :> string)->JSON.Encode.string),
("clientId", token.clientId->JSON.Encode.string),
("clientName", token.clientName->JSON.Encode.string),
("clientProfileId", token.clientProfileId->JSON.Encode.string),
("sessionId", paymentIntentID->JSON.Encode.string),
("publishableKey", publishableKey->JSON.Encode.string),
("emailAddress", token.email_address->JSON.Encode.string),
("transactionAmount", token.transaction_amount->JSON.Encode.string),
("transactionCurrencyCode", token.transaction_currency_code->JSON.Encode.string),
]->getJsonFromArrayOfJson,
),
("metadata", metadata),
])
}

React.useEffect0(() => {
let onPazeCallback = (ev: Window.event) => {
React.useEffect(() => {
let handlePazeCallback = ev => {
let json = ev.data->safeParse
let dict = json->Utils.getDictFromJson->getDictFromDict("data")
let isPaze = dict->getBool("isPaze", false)
if isPaze {
if dict->getBool("isPaze", false) {
setShowLoader(_ => false)
if dict->getOptionString("completeResponse")->Option.isSome {
let completeResponse = dict->getString("completeResponse", "")
Expand All @@ -61,14 +54,15 @@ let make = (~token: SessionsType.token) => {
}
}
}
Window.addEventListener("message", onPazeCallback)
Some(() => Window.removeEventListener("message", ev => onPazeCallback(ev)))
})

setIsShowOrPayUsing(_ => true)
Window.addEventListener("message", handlePazeCallback)
Some(() => Window.removeEventListener("message", handlePazeCallback))
}, [])
<button
disabled={showLoader}
onClick
className={`w-full flex flex-row justify-center items-center`}
className="w-full flex flex-row justify-center items-center"
style={
borderRadius: themeObj.buttonBorderRadius,
backgroundColor: "#2B63FF",
Expand Down
127 changes: 58 additions & 69 deletions src/Payments/PlaidSDKIframe.res
Original file line number Diff line number Diff line change
Expand Up @@ -8,122 +8,111 @@ let make = () => {
let (publishableKey, setPublishableKey) = React.useState(_ => "")
let (clientSecret, setClientSecret) = React.useState(_ => "")
let (isForceSync, setIsForceSync) = React.useState(_ => false)
let logger = React.useMemo(() => {
HyperLogger.make(~source=Elements(Payment), ~clientSecret, ~merchantId=publishableKey)
}, (publishableKey, clientSecret))
let logger = React.useMemo(
() => HyperLogger.make(~source=Elements(Payment), ~clientSecret, ~merchantId=publishableKey),
(publishableKey, clientSecret),
)

React.useEffect0(() => {
let handle = (ev: Window.event) => {
React.useEffect(() => {
let handleParentWindowMessage = (ev: Window.event) => {
let json = ev.data->safeParse
let metaData = json->getDictFromJson->getDictFromDict("metadata")
let linkToken = metaData->getString("linkToken", "")
if linkToken->String.length > 0 {
let pmAuthConnectorArray =
metaData
->getArray("pmAuthConnectorArray")
->Array.map(ele => ele->JSON.Decode.string)

if linkToken->String.length > 0 {
setLinkToken(_ => linkToken)
setPmAuthConnectorsArr(_ => pmAuthConnectorArray)
setPmAuthConnectorsArr(_ =>
metaData->getArray("pmAuthConnectorArray")->Array.map(JSON.Decode.string)
)
setPublishableKey(_ => metaData->getString("publishableKey", ""))
setClientSecret(_ => metaData->getString("clientSecret", ""))
setIsForceSync(_ => metaData->getBool("isForceSync", false))
}
}
Window.addEventListener("message", handle)
Window.addEventListener("message", handleParentWindowMessage)
messageParentWindow([("iframeMountedCallback", true->JSON.Encode.bool)])
Some(() => {Window.removeEventListener("message", handle)})
})
Some(() => Window.removeEventListener("message", handleParentWindowMessage))
}, [])

React.useEffect(() => {
PmAuthConnectorUtils.mountAllRequriedAuthConnectorScripts(
~pmAuthConnectorsArr,
~onScriptLoaded=authConnector => {
switch authConnector->PmAuthConnectorUtils.pmAuthNameToTypeMapper {
| PLAID => setIsReady(_ => true)
| NONE => ()
if authConnector->PmAuthConnectorUtils.pmAuthNameToTypeMapper === PLAID {
setIsReady(_ => true)
}
},
~logger,
)
None
}, [pmAuthConnectorsArr])

let callbackOnSuccessOfPlaidPaymentsFlow = () => {
open Promise
let callbackOnSuccessOfPlaidPaymentsFlow = async () => {
let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)]

PaymentHelpers.retrievePaymentIntent(
clientSecret,
headers,
~optLogger=Some(logger),
~customPodUri="",
~isForceSync=true,
)
->then(json => {
try {
let json = await PaymentHelpers.retrievePaymentIntent(
clientSecret,
headers,
~optLogger=Some(logger),
~customPodUri="",
~isForceSync=true,
)
let dict = json->getDictFromJson
let status = dict->getString("status", "")
let return_url = dict->getString("return_url", "")

if (
status === "succeeded" || status === "requires_customer_action" || status === "processing"
) {
switch status {
| "succeeded" | "requires_customer_action" | "processing" =>
postSubmitResponse(~jsonData=json, ~url=return_url)
} else if status === "failed" {
| "failed" =>
postFailedSubmitResponse(
~errortype="confirm_payment_failed",
~message="Payment failed. Try again!",
)
} else {
| _ =>
postFailedSubmitResponse(
~errortype="sync_payment_failed",
~message="Payment is processing. Try again later!",
)
}
messageParentWindow([("fullscreen", false->JSON.Encode.bool)])
resolve(json)
})
->then(_ => {
resolve(Nullable.null)
})
->catch(e => {
logInfo(Console.log2("Retrieve Failed", e))
resolve(Nullable.null)
})
->ignore
} catch {
| e => logInfo(Console.log2("Retrieve Failed", e))
}
}

React.useEffect(() => {
if isReady && linkToken->String.length > 0 {
let handler = Plaid.create({
token: linkToken,
onLoad: _ => {
logger.setLogInfo(~value="Plaid SDK Loaded", ~eventName=PLAID_SDK)
},
onSuccess: (publicToken, _) => {
let initializePlaid = () => {
Plaid.create({
token: linkToken,
onLoad: _ => logger.setLogInfo(~value="Plaid SDK Loaded", ~eventName=PLAID_SDK),
onSuccess: (publicToken, _) => {
messageParentWindow([
("isPlaid", true->JSON.Encode.bool),
("publicToken", publicToken->JSON.Encode.string),
])
if isForceSync {
callbackOnSuccessOfPlaidPaymentsFlow()->ignore
}
},
onExit: _ => {
if isForceSync {
callbackOnSuccessOfPlaidPaymentsFlow()->ignore
} else {
messageParentWindow([
("fullscreen", false->JSON.Encode.bool),
("isPlaid", true->JSON.Encode.bool),
("publicToken", publicToken->JSON.Encode.string),
("isExited", true->JSON.Encode.bool),
("publicToken", ""->JSON.Encode.string),
])
if isForceSync {
callbackOnSuccessOfPlaidPaymentsFlow()
}
},
onExit: _ => {
if isForceSync {
callbackOnSuccessOfPlaidPaymentsFlow()
} else {
messageParentWindow([
("fullscreen", false->JSON.Encode.bool),
("isPlaid", true->JSON.Encode.bool),
("isExited", true->JSON.Encode.bool),
("publicToken", ""->JSON.Encode.string),
])
}
},
})
}
},
}).open_()
}

handler.open_()
React.useEffect(() => {
if isReady && linkToken->String.length > 0 {
initializePlaid()
}

None
Expand Down
Loading

0 comments on commit 68a1e15

Please sign in to comment.