0

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?

Jun Mallari
  • 25
  • 1
  • 7

1 Answers1

1

You should not have problems with the addNewRecord failing, considering your code. Due to the fact that the function will only be called, based in specific and controlled scenarios, in which you will have the parameters needed for the function to be called correctly, you should be fine.

Anyway, it's very probably that if it failed once, it will fail again, so, you can try to work with a queue system instead of just trying to repeat the execution. This way, you will maintain that data in a queue and run again after checking and handling of the error, to ensure that the addition of the record will occur.

I would recommend you to take a look at the following documents, on queuing with Javascript, that I believe might help you.

Let me know if the information helped you!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22
  • Great advice. I will develop the queue system and come back to you once I've tested it. Thanks. – Jun Mallari May 13 '20 at 04:52
  • No problem! Great to hear it helps! Please, considering upvoting or accepting it! :) – gso_gabriel May 13 '20 at 10:04
  • Here's the [link](https://repl.it/@stoic25/HandlingUnexpectedFailure) for the attempt to have `addNewRecord` function with a queue system. Let me know what you think. – Jun Mallari May 14 '20 at 00:55