繁体   English   中英

为什么 firestore 在云 function 成功完成后几分钟更新文档?

[英]why firestore updates the document few minutes after successful cloud function completion?

我正在使用可调用云 function 来更新用户用户名,function 大部分时间都有效,但偶尔在 function 成功完成后,最多需要3 分钟才能在 firestore 中看到更新后的用户名。

只要有2个问题:

  1. 随机时间如此缓慢的原因是什么?

  2. 在前面,我收到“已成功更改用户名”的响应,尽管这不是真的,因为 firestore 还没有真正更新任何东西,因此,由于这一切,我什至无法使我的查询无效。

export const addUsername = functions
  .region("us-central1", "europe-west2")
  .https.onCall(async (data: string, context) => {
    if (context.auth?.uid) {
      // check if a new username is available
      const userId = context.auth.uid;
      const db = getFirestore();
      const batch = db.batch();
      const docRef = db.collection("usernames").doc(data);
      const userPublicRef = db.collection("usersPublic").doc(userId);
      const usersPrivateRef = db.collection("users").doc(userId);
      docRef
        .get()
        .then(async (doc) => {
          if (!doc.exists) {
            // adds new username to usernames, usersPublic, users collections
            batch.set(docRef, {
              uid: userId,
            });
            batch.set(userPublicRef, { username: data }, { merge: true });
            batch.set(usersPrivateRef, { username: data }, { merge: true });
            const oldUsernameSnap = await admin
              .firestore()
              .collection("usernames")
              .where("uid", "==", userId)
              .get();
            // deletes the old username which makes it available for others
            oldUsernameSnap.forEach((doc) => batch.delete(doc.ref));
            batch.commit();
          } else {
            throw new Error("Document already exists");
          }
        })
        .catch(() => {
          throw new Error("Something went wrong");
        });
      return {
        message: "successfully changed the username",
      };
    }
    return {
      message: "not authenticated",
    };
  });

当然,我可以只通知用户“更改最多可能需要 3 分钟”,但这不是我想要做的,我真的很感激有关他的一些信息。

您确实在获取 docRef 之前返回了响应。 尝试在 docRef.get 之前添加一个返回,然后在提交批处理后返回响应。

return docRef.get().then(async (doc) => {
   ...
   await batch.commit()
   return { message: "updated" }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM