javascript 为什么Firebase事务会变慢?

dwbf0jvd  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(151)

我有一个函数,每当用户创建一个新文档(参与事件)时,它都会运行。我使用事务是因为在某些情况下,新的参与文档创建得很快,我希望避免争用条件。但在这种情况下,此函数通常需要40-120秒才能运行。

export const esLatDailyAggr = async (
  uid: admin.firestore.DocumentReference,
  eventTypeId: admin.firestore.DocumentReference,
  timestamp: Date,
  clientId: admin.firestore.DocumentReference,
  year: number,
  month: number,
  day: number) => {
  const startTime = Date.now();
  console.log("Starting to update daily aggr data.");
  const docId = `${uid.id}-${year}-${month}-${day}`; // create composite key

  const statsRefAggr = admin.firestore().collection("dailyAggregateData");
  const queryAggr = statsRefAggr.doc(docId);
  await admin.firestore().runTransaction(async (transaction) => {
    const queryAggrSnapshot = await transaction.get(queryAggr);

    if (!queryAggrSnapshot.exists) { // check if document exists
      console.log(
        docId, " Daily doc not found. Creating new one by new Participation");
      // create new document with composite key
      transaction.set(queryAggr, {
        uid: uid,
        year: year,
        month: month,
        day: day,
        NoOfParticipations: 1,
        ActiveClientsId: [clientId],
        ActiveEventTypeId: [eventTypeId],
        timestamp: timestamp,
      });
    } else {
      // update existing document
      transaction.update(queryAggr, {
        NoOfParticipations: admin.firestore.FieldValue.increment(1),
        ActiveClientsId: admin.firestore.FieldValue.arrayUnion(clientId),
        ActiveEventTypeId: admin.firestore.FieldValue.arrayUnion(eventTypeId),
      });
      console.log(docId, " Daily aggr data updated by new Participation.");
    }
  });
  const endTime = Date.now();
  console.log("Daily Aggr Data function finished. Running Time: ",
  endTime - startTime, "ms");
};

有什么办法可以让它明显地更快吗?

tcbh2hod

tcbh2hod1#

有很多方法可以优化你的函数,但是有一种方法可以显著地提高它的速度,那就是对你正在执行的每条语句都进行return。例如:

transaction
.set(queryAggr, {
    uid: uid,
    year: year,
    month: month,
    day: day,
    NoOfParticipations: 1,
    ActiveClientsId: [clientId],
    ActiveEventTypeId: [eventTypeId],
    timestamp: timestamp,
})
.then(function (result) {
    console.log(result);
    const endTime = Date.now();
    console.log("Daily Aggr Data function finished. Running Time: ",
    endTime - startTime, "ms");

    return;
});

相关问题