【问题标题】:Batch write with Firebase Cloud Functions使用 Firebase Cloud Functions 批量写入
【发布时间】:2022-01-18 22:43:39
【问题描述】:

我使用 Firebase 作为我的 iOS 应用程序的后端,但不知道如何通过他们的 Cloud Functions 构建批量写入。

我的 Firestore 中有两个系列,饮料和客户。每个新饮料和每个新客户都分配有一个 userId 属性,该属性对应于当前登录用户的 uid。 userId 与 Firestore 的查询一起使用,以仅获取与登录用户相关联的饮料和客户,如下所示:Firestore.firestore().collection("customers").whereField("userId", isEqualTo: Auth.auth().currentUser.uid)

用户可以匿名登录,也可以匿名订阅。问题是如果他们注销,就无法重新登录到相同的匿名 uid。 uid 还使用 RevenueCat SDK 存储为 appUserID,因此我仍然可以访问它,但是由于我无法使用 uid 将用户重新登录到他们的匿名帐户,因此这是帮助用户访问其数据的唯一方法恢复购买的情况是将其数据的userId字段从旧的uid更新为新的uid。这就是需要批量写入的地方。

一般来说,我对编程比较陌生,但对于 Cloud Functions、JavaScript 和 Node.js,我非常陌生。虽然我在网上四处游荡,并认为我找到了一个解决方案,我制作了一个可调用的云函数,并使用数据对象发送旧用户 ID 和新用户 ID,使用旧用户 ID 查询文档的集合并将它们的 userId 字段更新为新的.不幸的是,它不起作用,我不知道为什么。

我的代码如下所示:

// Cloud Function

exports.transferData = functions.https.onCall((data, context) => {
  const firestore = admin.firestore();
  const customerQuery = firestore.collection('customers').where('userId', '==', `${data.oldUser}`);
  const drinkQuery = firestore.collection('drinks').where('userId', '==', `${data.oldUser}`);

  const customerSnapshot = customerQuery.get();
  const drinkSnapshot = drinkQuery.get();
  const batch = firestore.batch();

  for (const documentSnapshot of customerSnapshot.docs) {
    batch.update(documentSnapshot.ref, { 'userId': `${data.newUser}` });
  };
  for (const documentSnapshot of drinkSnapshot.docs) {
    batch.update(documentSnapshot.ref, { 'userId': `${data.newUser}` });
  };
  return batch.commit();
});
// Call from app

func transferData(from oldUser: String, to newUser: String) {
    let functions = Functions.functions()
    
    functions.httpsCallable("transferData").call(["oldUser": oldUser, "newUser": newUser]) { _, error in
        if let error = error as NSError? {
            if error.domain == FunctionsErrorDomain {
                let code = FunctionsErrorCode(rawValue: error.code)
                let message = error.localizedDescription
                let details = error.userInfo[FunctionsErrorDetailsKey]
                print(code)
                print(message)
                print(details)
            }
        }
    }
}

这是来自 Cloud Functions 日志的错误消息:

Unhandled error TypeError: customerSnapshot.docs is not iterable
    at /workspace/index.js:22:51
    at fixedLen (/workspace/node_modules/firebase-functions/lib/providers/https.js:66:41)
    at /workspace/node_modules/firebase-functions/lib/common/providers/https.js:385:32
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

据我了解,customerSnapshot 是一种叫做 Promise 的东西,我猜这就是为什么我不能迭代它。到目前为止,我的知识太少了,不知道如何处理查询返回的这些 Promise。

我想我可以强制用户在订阅之前创建一个登录名,但既然我已经走到了这一步,那感觉就像是一种懦夫的出路。我宁愿两个选项都可用并做出决定,而不是走上强制的道路。另外,如果我弄明白了,我会学习更多的 JavaScript!

非常感谢任何和所有帮助!

编辑:

解决方案:

// Cloud Function

exports.transferData = functions.https.onCall(async(data, context) => {
  const firestore = admin.firestore();
  const customerQuery = firestore.collection('customers').where('userId', '==', `${data.oldUser}`);
  const drinkQuery = firestore.collection('drinks').where('userId', '==', `${data.oldUser}`);

  const customerSnapshot = await customerQuery.get();
  const drinkSnapshot = await drinkQuery.get();
  const batch = firestore.batch();

  for (const documentSnapshot of customerSnapshot.docs.concat(drinkSnapshot.docs)) {
    batch.update(documentSnapshot.ref, { 'userId': `${data.newUser}` });
  };
  
  return batch.commit();
});

【问题讨论】:

    标签: javascript node.js swift firebase google-cloud-functions


    【解决方案1】:

    正如您已经猜到的那样,调用 customerQuery.get() 返回一个承诺。

    为了了解你需要什么,你应该先在这里熟悉一下promise的概念:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    对于您的用例,您最终可能会使用 then 回调:

    customerQuery.get().then((result) => {
        // now you can access the result
    }
    

    或通过使用await 语句使方法调用同步:

    const result = await customerQuery.get()
    // now you can access the result
    

    【讨论】:

    • 非常感谢您!我阅读了您提供的链接,它并不像我担心的那么复杂。我选择了 await 路线,感觉就像一个巧妙的解决方案。像魅力一样工作!
    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多