使用云任务和云功能

时间:2020-04-30 20:08:38

标签: node.js firebase google-cloud-firestore google-cloud-functions google-cloud-tasks

我在这里尝试使用具有云功能的云任务,以便当我的集合的字段设置为true时,任务将在24小时后将其自动设置为false。 但是我不太了解有关使用云任务和云功能的所有内容,因此我确实需要一些帮助...

我如何获取要发送到Http云函数中的Trigger onUpdate Cloud函数的userId值,以便我可以使用它来更新特定字段(即地图)?

这是我的功能:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const { CloudTasksClient } = require('@google-cloud/tasks');

admin.initializeApp()
    exports.onUpdateSavedPostsReUpdateItLater = functions.firestore
      .document("/saved/{userId}/savedPosts/{postId}")
      .onUpdate(async (change, context) => {
        const userId = context.params.userId;
        const postUpdate = change.after.data();
        const pStatus = postUpdate.prayers[userId]; // The field that i want to update


        updateAtSeconds = Date.now() / 1000 + 86400; //86400 equal to 24 hours, because i want my documents to be updated in the next 24 hours


        // Get the project ID from the FIREBASE_CONFIG env var
        const project = JSON.parse(process.env.FIREBASE_CONFIG!).projectId;
        const location = 'europe-west3';
        const queue = 'ijn-amen';

        const tasksClient = new CloudTasksClient();
        const queuePath: string =
          tasksClient.queuePath(project, location, queue);


        const url = 'https://${location}-${project}.cloudfunctions.net/firestoreTtlCallback';
        const docPath = change.ref.path;
        const payload: UpdateTaskPayload = { docPath };

        const task = {
          httpRequest: {
            httpMethod: 'POST',
            url,
            body: Buffer.from(JSON.stringify(payload)).toString('base64'),
            headers: {
              'Content-Type': 'application/json',
            },
          },
          scheduleTime: {
            seconds: updateAtSeconds
          }
        };

        const [response] = await tasksClient.createTask({ parent: queuePath, task });

        console.log('Created task ${response.name}');
      });



    export const firestoreTtlCallback =
      functions.https.onRequest(async (req, res) => {
        const payload = req.body as UpdateTaskPayload
        try {
          await admin.firestore().doc(payload.docPath).update({ 'prayers.${userId}': false });
          res.send(200);
        }
        catch (error) {
          console.error(error);
          res.status(500).send(error);
        }
      });

谢谢

0 个答案:

没有答案