UNPKG

@yihuangdb/storage-object

Version:

A Node.js storage object layer library using Redis OM

81 lines 2.39 kB
"use strict"; /** * Atomic batch operations for StorageObject * Provides true atomicity for batch create, update, and delete operations */ Object.defineProperty(exports, "__esModule", { value: true }); exports.RollbackManager = exports.BatchOperationError = void 0; exports.entityToHash = entityToHash; exports.executeInChunks = executeInChunks; class BatchOperationError extends Error { operation; failedCount; successCount; errors; constructor(message, operation, failedCount, successCount, errors) { super(message); this.operation = operation; this.failedCount = failedCount; this.successCount = successCount; this.errors = errors; this.name = 'BatchOperationError'; } } exports.BatchOperationError = BatchOperationError; /** * Helper to convert entity to Redis hash format */ function entityToHash(entity) { const hash = {}; for (const [key, value] of Object.entries(entity)) { if (value !== undefined && value !== null) { if (typeof value === 'object') { hash[key] = JSON.stringify(value); } else { hash[key] = String(value); } } } return hash; } /** * Execute operations in chunks for better performance */ async function executeInChunks(items, chunkSize, operation) { const results = []; for (let i = 0; i < items.length; i += chunkSize) { const chunk = items.slice(i, i + chunkSize); const chunkResults = await operation(chunk); results.push(...(Array.isArray(chunkResults) ? chunkResults : [chunkResults])); } return results; } /** * Rollback helper for failed operations */ class RollbackManager { rollbackActions = []; addRollback(action) { this.rollbackActions.push(action); } async executeRollback() { let rolledBack = 0; // Execute rollbacks in reverse order for (const action of this.rollbackActions.reverse()) { try { await action(); rolledBack++; } catch (error) { console.error('Rollback failed:', error); } } return rolledBack; } clear() { this.rollbackActions = []; } } exports.RollbackManager = RollbackManager; //# sourceMappingURL=batch-operations.js.map