cloudtasks
v1.0.0
Published
Google Cloud Tasks API implementation
Readme
CloudTasks Library
A Node.js library for interacting with the Google Cloud Tasks API. It provides a simple and efficient interface for queuing tasks using a Cloud Tasks queue.
Features
- Task Management: Create and delete tasks in a Google Cloud Tasks queue.
- Retry Mechanism: Handles transient errors with configurable retries and delays.
- Service Account Authentication: Easily integrates with Google service accounts for secure access.
Installation
pnpm installUsage
1. Setting Up a Service Account
- Go to the Google Cloud Console.
- Create or download a service account JSON key file with the
Cloud Tasks Enqueuerrole. - Note the path to the service account JSON key file.
2. Import and Initialize CloudTasks
Initialize the CloudTasks class and ensure to call initialize with the path to the service account key file before processing tasks.
import { CloudTasks, ACTIONS } from "../../dist";
import fs from "fs";
const serviceAccountPath = "service-account.json";
function init() {
const cloudTasks = new CloudTasks(
"avid-invention-157405", // Google Cloud project ID
"australia-southeast1", // Location of the Cloud Tasks queue
"barbecue", // Name of the Cloud Tasks queue
"https://typically-communal-sunbeam.ngrok-free.app/tasks/callback", // Path for the task callback
serviceAccountPath // Path to the service account JSON file
);
return cloudTasks;
}
async function mainWithServiceFile() {
const cloudTasks = init();
await cloudTasks.initialize({ serviceAccountPath });
const task = cloudTasks.generateTaskPayload({ key: "test-value" });
console.log("Calling API with service account file");
const createdTask = await cloudTasks.processTask(task, ACTIONS.CREATE);
console.log("Task created:", createdTask);
}
async function mainWithCredentials() {
const cloudTasks = init();
const creds = fs.readFileSync(serviceAccountPath, "utf-8");
await cloudTasks.initialize({ credentials: creds });
const task = cloudTasks.generateTaskPayload({ key: "test-value" });
console.log("Calling API with credentials");
const createdTask = await cloudTasks.processTask(task, ACTIONS.CREATE);
console.log("Task created:", createdTask);
}
mainWithServiceFile().catch(console.error);
mainWithCredentials().catch(console.error);API Reference
Class: CloudTasks
Constructor
new CloudTasks(
project_id: string,
location: string,
queue: string,
callbackPath: string
);Parameters:
project_id: Google Cloud project ID.location: The location/region of the Cloud Tasks queue.queue: Name of the Cloud Tasks queue.callbackPath: Path for task callbacks.
Methods
initialize({serviceAccountPath: string, credentials: string}): Promise<void>
Initializes the CloudTasks instance by authenticating with the service account.
Parameters:
serviceAccountPath: Path to the Google service account JSON key file.credentials: Google service account JSON key file.
processTask(task: Record<string, any>, type: ACTIONS): Promise<any>
Processes a task by creating or deleting it.
Parameters:
task: The task payload to process.type: The type of action (ACTIONS.CREATEorACTIONS.DELETE).
overrideRetryDelay(delay: number, retries: number): void
Overrides the default retry delay and maximum retries.
Parameters:
delay: Retry delay in milliseconds.retries: Maximum number of retries.
createTask(task: Record<string, any>): Promise<any>
Creates a task in the queue.
Parameters:
task: The task payload.
deleteTask(taskName: string): Promise<any>
Deletes a task from the queue.
Parameters:
taskName: Name of the task to delete.
Customization
Configure Retry Logic
The default retry configuration can be overridden using the overrideRetryDelay method:
cloudTasks.overrideRetryDelay(500, 3); // Set retry delay to 500ms and max retries to 3Error Handling
The library throws detailed errors when tasks fail to be created or deleted. Common issues include:
- Invalid service account credentials.
- Insufficient permissions for the service account.
- Network or server errors.
Use try-catch blocks to handle errors:
try {
await cloudTasks.createTask(taskPayload);
} catch (error) {
console.error("Failed to create task:", error.message);
}Example Task Payload
Here’s an example of a task payload for creating an HTTP task:
const taskPayload = {
httpRequest: {
httpMethod: "POST",
url: "https://example.com/task-handler",
body: Buffer.from(JSON.stringify({ key: "value" })).toString("base64"),
headers: {
"Content-Type": "application/json",
},
},
};