I have a callable initiatePayment
function below that process the payment of a user when they pay from client side. This records a new document to my firestore database if the payment is success (addNewRecord
) then finally returns payment data from the response of the request.
export const initiatePayment = functions.https.onCall(async (data, context) => {
// destructure data argument
const { userId } = data;
try {
// 1. Process payment via external API request
const payment = await paymentExternalRequest();
const { paymentData, status } = payment.response;
// 2. If payment processing was a success, record new payment data
if (status === "succeeded") {
addNewRecord(userId, paymentData);
}
// 3. Return paymentData to client
return paymentData;
} catch (error) {
throw new functions.https.HttpsError("cancelled", "Cancelled", error);
}
});
addNewRecord
function:
const addNewRecord = async (userId, paymentData) => {
const newRecordToAdd = { userId, paymentData };
const docRef = admin
.firestore()
.collection("transactions")
.doc(paymentData.id);
try {
const newRecord = await docRef.set({ userId, transaction: newRecordToAdd });
return newRecord;
} catch (error) {
console.log(error);
}
};
My question is what if addNewRecord
fails, how do you handle its error and retry the function again to ensure its success?