Home > Enterprise >  Create a new Cloud Task in Firebase from Each file I find in a db collection get?
Create a new Cloud Task in Firebase from Each file I find in a db collection get?

Time:03-11

I am looking to create a cloud task to run on each file I find in a collection.

I have looked at 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 but it doesn't work for me needs. I need to be able to run through Each document found from the db.collections(myCollection").get() method and create a cloud task to check a response from an API and update this document.

So far I have

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 })

      });

I am aware that I ideally need an await for

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

I of course cannot do this in a forEach, and a for(let x in querySnapshot) won't work for this.

Whats the best way to approach my scenario in Firebase? Thanks!

CodePudding user response:

The code you wrote looks good. I'm able to create a Cloud Task using that code with a little bit of modification. You can use the .map and the modern for loop instead of .foreach after getting the collection. See code below:

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}`);
    }

The above code will log like this:

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

Let me know if you have any concerns.

  • Related