从我在数据库集合中找到的每个文件在 Firebase 中创建一个新的 Cloud Task

Create a new Cloud Task in Firebase from Each file I find in a db collection get

我希望为我在集合中找到的每个文件创建一个云任务 运行。

我看过 https://medium.com/firebase-developers/how-to-schedule-a-cloud-function-to-run-in-the-future-in-order-to-build-a-firestore-document-ttl-754f9bf3214a 但它不适合我的需要。

我需要能够 运行 通过从 db.collections(myCollection").get() 方法找到的每个文档并创建一个云任务来检查来自 API 并更新此文档。

到目前为止我有:

const querySnapshot= await db.collection("pending").get()

querySnapshot.forEach((doc) =>{
        //updateAssetPendingInfo(doc) //YOU ARE HERE

        const project = "myProject"
        const queue = 'firestore-function'
        const location = 'europe-west1'
        const tasksClient = new CloudTasksClient()
        const queuePath = tasksClient.queuePath(project, location, queue)
        const url = `https://${location}-${project}.cloudfunctions.net/firestoreHelperFunctionsCallback`
        const docPayload = doc
        const payload = { docPayload }
        const task = {
          httpRequest: {
            httpMethod: 'POST',
            url,
            body: Buffer.from(JSON.stringify(payload)).toString('base64'),
            headers: {
              'Content-Type': 'application/json',
            },
          },
          scheduleTime: {
            seconds: 10
          }
      }
      tasksClient.createTask({ parent: queuePath, task })

      });

我知道我理想情况下需要等待:

tasksClient.createTask({ parent: queuePath, task })

我当然不能在 forEach 中执行此操作,并且 for(let x in querySnapshot) 对此不起作用。

在 Firebase 中处理我的场景的最佳方法是什么?

你写的代码看起来不错。我可以使用该代码稍作修改来创建 Cloud Task。获取集合后,您可以使用 .map 和现代 for 循环代替 .foreach。请参阅下面的代码:

const querySnapshot= await db.collection("pending").get()
const documents = querySnapshot.docs.map((doc) => ({ ...doc.data() }));

    for(const doc of documents){
        const project = "myProject"
        const queue = 'firestore-function'
        const location = 'europe-west1'
        const tasksClient = new CloudTasksClient()
        const queuePath = tasksClient.queuePath(project, location, queue)
        const url = `https://${location}-${project}.cloudfunctions.net/firestoreHelperFunctionsCallback`
        const docPayload = doc
        const payload = { docPayload }
        const task = {
            httpRequest: {
                httpMethod: 'POST',
                url,
                body: Buffer.from(JSON.stringify(payload)).toString('base64'),
                headers: {
                'Content-Type': 'application/json',
                },
            },
            scheduleTime: {
                seconds: 10
            }
        }
        const [response] =  await tasksClient.createTask({ 
            parent: queuePath,
            task });
        console.log(`Created task ${response.name}`);
    }

上面的代码会这样记录:

Created task projects/myProject/locations/europe-west1/queues/firestore-function/tasks/64659584099220357431

如果您有任何疑虑,请告诉我。