// WordPress Batch Operations Service
import { AxiosInstance } from 'axios';
import { logger } from '../../utils/logger.js';
import { ErrorHandler, MCPError, ErrorCategory } from '../../utils/error-handler.js';
export interface BatchOperation {
type: 'create' | 'update' | 'delete';
endpoint: string;
data?: any;
id?: number;
}
export interface BatchResult {
success: boolean;
operation: BatchOperation;
result?: any;
error?: string;
}
export interface BatchOptions {
stopOnError?: boolean;
continueOnError?: boolean;
}
export class BatchService {
constructor(private client: AxiosInstance) {}
async executeBatch(
operations: BatchOperation[],
options: BatchOptions = { continueOnError: true }
): Promise<{ results: BatchResult[]; summary: any }> {
return ErrorHandler.wrapAsync(async () => {
logger.info(`Executing batch of ${operations.length} operations`);
const results: BatchResult[] = [];
let successCount = 0;
let errorCount = 0;
for (let i = 0; i < operations.length; i++) {
const operation = operations[i];
if (!operation) continue;
try {
logger.debug(`Executing operation ${i + 1}/${operations.length}`, operation);
let result;
switch (operation.type) {
case 'create':
result = await this.client.post(operation.endpoint, operation.data);
break;
case 'update':
result = await this.client.post(`${operation.endpoint}/${operation.id}`, operation.data);
break;
case 'delete':
result = await this.client.delete(`${operation.endpoint}/${operation.id}`);
break;
}
results.push({
success: true,
operation,
result: result?.data
});
successCount++;
} catch (error: any) {
logger.error(`Batch operation ${i + 1} failed`, error);
errorCount++;
results.push({
success: false,
operation,
error: error.message || 'Unknown error'
});
if (options.stopOnError) {
logger.warn('Stopping batch due to error');
break;
}
}
}
const summary = {
total: operations.length,
success: successCount,
failed: errorCount,
completed: results.length
};
logger.info('Batch execution complete', summary);
return { results, summary };
}, 'BatchService.executeBatch');
}
async batchCreatePosts(postType: string, posts: any[]): Promise<any> {
const operations: BatchOperation[] = posts.map(post => ({
type: 'create',
endpoint: `/${postType}`,
data: post
}));
return this.executeBatch(operations);
}
async batchUpdatePosts(postType: string, updates: Array<{ id: number; data: any }>): Promise<any> {
const operations: BatchOperation[] = updates.map(update => ({
type: 'update',
endpoint: `/${postType}`,
id: update.id,
data: update.data
}));
return this.executeBatch(operations);
}
async batchDeletePosts(postType: string, ids: number[]): Promise<any> {
const operations: BatchOperation[] = ids.map(id => ({
type: 'delete',
endpoint: `/${postType}`,
id
}));
return this.executeBatch(operations);
}
}