Rogier
Rogier

Reputation: 550

How to get the autogenerated task name from Google Cloud Tasks when adding Firebase Task queue functions?

Following the Cloud Functions documentation about how to Enqueue functions with Cloud Tasks it is demonstrated how to create a Firebase task queue function. This works all fine.

However, if I call the enqueue to enqueue the function a Promise without any information whatsoever on my queued task is returned.

→ How can I get the task name or any reference from the just created task that is added to my queue?

I need this name to store, so I can possibly cancel my task before execution.

Upvotes: 2

Views: 708

Answers (1)

Rogier
Rogier

Reputation: 550

As it seems to be, Firestore Cloud functions have a limited feature set in comparison to the "real" Google Cloud Functions.

To get more data on the task, do not use the enqueue function from firebase-admin/functions, but make use of the @google-cloud/tasks library:


// Imports the Google Cloud Tasks library.
import { protos, CloudTasksClient } from "@google-cloud/tasks";

// Set all the details for the function to call
const serviceAccountEmail = "[email protected]";
const project = "PROJECT_ID";
const queue = "my-queue";
const location = "europe-west1";
const url =
    "https://europe-west1-PROJECT_ID.cloudfunctions.net/yourFunctionToCall";

const client = new CloudTasksClient();
const formattedParent = client.queuePath(project, location, queue);

const payload = {
  data: {
    your: "data"
  },
};

const task = {
  httpRequest: {
    httpMethod: "POST",
    url: url,
    body: Buffer.from(JSON.stringify(payload)).toString("base64"),
    headers: {
      "Content-Type": "application/json",
    },
    oidcToken: {
      serviceAccountEmail,
    },
  },
  scheduleTime: {
    seconds: Date.now() / 1000, // Any epcoch time in seconds, or do not set for immediate execution
  },
} as protos.google.cloud.tasks.v2beta3.ITask;

const request = {
  parent: formattedParent,
  task: task,
};

const [response] = await client.createTask(request);
functions.logger.info(`Created task ${response.name}`);

Calling client.createTask will return data on the Task. This allows you to also remove the Task if necessary.

Upvotes: 3

Related Questions