cloudflare/ts/cloudflare.classes.workermanager.ts

130 lines
4.3 KiB
TypeScript

import * as plugins from './cloudflare.plugins.js';
import { CloudflareAccount } from './cloudflare.classes.account.js';
import { CloudflareWorker } from './cloudflare.classes.worker.js';
import { logger } from './cloudflare.logger.js';
export class WorkerManager {
public cfAccount: CloudflareAccount;
constructor(cfAccountArg: CloudflareAccount) {
this.cfAccount = cfAccountArg;
}
/**
* Creates a new worker or updates an existing one
* @param workerName Name of the worker
* @param workerScript JavaScript content of the worker
* @returns CloudflareWorker instance for the created/updated worker
*/
public async createWorker(workerName: string, workerScript: string): Promise<CloudflareWorker> {
if (!this.cfAccount.preselectedAccountId) {
throw new Error('No account selected. Please select it first on the account.');
}
try {
// Create or update the worker script
await this.cfAccount.apiAccount.workers.scripts.content.update(workerName, {
account_id: this.cfAccount.preselectedAccountId,
"CF-WORKER-BODY-PART": workerScript,
metadata: {} // Required empty object
});
// Create a new worker instance directly
const worker = new CloudflareWorker(this);
worker.id = workerName;
// Initialize the worker and get its routes
await worker.getRoutes();
return worker;
} catch (error) {
logger.log('error', `Failed to create worker ${workerName}: ${error.message}`);
throw error;
}
}
/**
* Get a worker by name
* @param workerName Name of the worker to retrieve
* @returns CloudflareWorker instance or undefined if not found
*/
public async getWorker(workerName: string): Promise<CloudflareWorker | undefined> {
if (!this.cfAccount.preselectedAccountId) {
throw new Error('No account selected. Please select it first on the account.');
}
try {
// Check if the worker exists
await this.cfAccount.apiAccount.workers.scripts.get(workerName, {
account_id: this.cfAccount.preselectedAccountId
});
// Create a new worker instance directly
const worker = new CloudflareWorker(this);
worker.id = workerName;
// Initialize the worker and get its routes
await worker.getRoutes();
return worker;
} catch (error) {
logger.log('warn', `Worker '${workerName}' not found: ${error.message}`);
return undefined;
}
}
/**
* Lists all worker scripts
* @returns Array of worker scripts
*/
public async listWorkerScripts() {
if (!this.cfAccount.preselectedAccountId) {
throw new Error('No account selected. Please select it first on the account.');
}
try {
const result = await this.cfAccount.apiAccount.workers.scripts.list({
account_id: this.cfAccount.preselectedAccountId,
});
// Check if the result has a 'result' property (API response format)
if (result && result.result && Array.isArray(result.result)) {
return result.result;
}
// Otherwise collect from async iterator (new client format)
const workerScripts: plugins.ICloudflareTypes['Script'][] = [];
for await (const scriptArg of this.cfAccount.apiAccount.workers.scripts.list({
account_id: this.cfAccount.preselectedAccountId,
})) {
workerScripts.push(scriptArg);
}
return workerScripts;
} catch (error) {
logger.log('error', `Failed to list worker scripts: ${error.message}`);
return [];
}
}
/**
* Deletes a worker script
* @param workerName Name of the worker to delete
* @returns True if deletion was successful
*/
public async deleteWorker(workerName: string): Promise<boolean> {
if (!this.cfAccount.preselectedAccountId) {
throw new Error('No account selected. Please select it first on the account.');
}
try {
await this.cfAccount.apiAccount.workers.scripts.delete(workerName, {
account_id: this.cfAccount.preselectedAccountId
});
logger.log('info', `Worker '${workerName}' deleted successfully`);
return true;
} catch (error) {
logger.log('error', `Failed to delete worker '${workerName}': ${error.message}`);
return false;
}
}
}