@mbc-cqrs-serverless/import
Version:
146 lines • 7.97 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var ImportQueueEventHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImportQueueEventHandler = void 0;
/**
* @file import.queue.event.handler.ts
* @description This handler is the core worker for processing individual import records.
* It listens for messages from the main SQS queue, finds the correct processing
* strategy for the record's table type, and executes them sequentially.
*/
const core_1 = require("@mbc-cqrs-serverless/core");
const common_1 = require("@nestjs/common");
const constant_1 = require("../constant");
const comparison_status_enum_1 = require("../enum/comparison-status.enum");
const import_status_enum_1 = require("../enum/import-status.enum");
const helpers_1 = require("../helpers");
const import_module_definition_1 = require("../import.module-definition");
const import_service_1 = require("../import.service");
const import_queue_event_1 = require("./import.queue.event");
let ImportQueueEventHandler = ImportQueueEventHandler_1 = class ImportQueueEventHandler {
constructor(importService, strategyMap) {
this.importService = importService;
this.strategyMap = strategyMap;
this.logger = new common_1.Logger(ImportQueueEventHandler_1.name);
}
async execute(event) {
const importEntity = event.importEvent.importEntity;
if (!importEntity.id.startsWith(`${constant_1.IMPORT_PK_PREFIX}${core_1.KEY_SEPARATOR}`)) {
this.logger.debug(`Skipping other type import job in main queue handler: ${importEntity.id}`);
return;
}
await this.handleImport(event);
}
/**
* Orchestrates the processing of a single import record.
*/
async handleImport(event) {
const importKey = event.importEvent.importKey;
const importEntity = event.importEvent.importEntity;
const { attributes, tenantCode, type: tableName } = importEntity;
this.logger.debug(`Processing import job ${importKey.pk}#${importKey.sk} for table: ${tableName}`);
// 1. Find the correct strategies for this import's table type
const strategy = this.strategyMap.get(tableName);
if (!strategy) {
const error = new Error(`No import strategies registered for table: ${tableName}`);
this.logger.error(error);
await this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.FAILED, { error: error.stack });
return;
}
try {
// 2. Set status to PROCESSING
await this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.PROCESSING);
// 3. Execute all registered strategies in sequence for this record
await this.executeStrategy(strategy, attributes, tenantCode, importEntity);
// // 4. Finalize the import status as COMPLETED
// await this.importService.updateStatus(
// importKey,
// ImportStatusEnum.COMPLETED,
// { result },
// )
// this.logger.log(
// `Successfully completed import job: ${importKey.pk}#${importKey.sk}`,
// )
}
catch (error) {
// 5. Handle any errors during processing
this.logger.error(`Failed to process import job: ${importKey.pk}#${importKey.sk}`, error);
await Promise.all([
this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.FAILED, {
error: {
message: error.message,
stack: error.stack,
},
}),
this.importService.publishAlarm(event, error.stack),
]);
throw error;
}
}
/**
* Executes the full lifecycle (compare, map, save) for a single strategy.
* @returns The result of the create/update operation or a status message.
*/
async executeStrategy(strategy, attributes, tenantCode, importEntity) {
// 1. Determine if there are changes
const compareResult = await strategy.compare(attributes, tenantCode);
const importKey = {
pk: importEntity.pk,
sk: importEntity.sk,
};
if (compareResult.status === comparison_status_enum_1.ComparisonStatus.EQUAL) {
this.logger.log(`No changes for import job ${importEntity.id}, marking as completed.`);
await this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.COMPLETED, { result: { status: 'EQUAL', message: 'No changes detected.' } });
const skParts = importEntity.sk.split(core_1.KEY_SEPARATOR);
const parentId = skParts.slice(0, -1).join(core_1.KEY_SEPARATOR);
if (parentId.startsWith(constant_1.CSV_IMPORT_PK_PREFIX)) {
this.logger.debug(`Updating parent job counter for EQUAL status child: ${importEntity.id}`);
const parentKey = (0, helpers_1.parseId)(parentId);
// Since the status is EQUAL, the child "succeeded" in its processing.
await this.importService.incrementParentJobCounters(parentKey, true);
}
return; // Stop execution for this case
}
// 2. Map the attributes to the correct CommandService input model
// The strategy now handles the logic of building the payload.
const mappedData = await strategy.map(compareResult.status, attributes, tenantCode, compareResult.existingData);
const commandService = strategy.getCommandService();
let result;
// 3. Execute the appropriate command
const invokeContext = (0, core_1.extractInvokeContext)();
const options = {
invokeContext,
source: importEntity.id,
};
if (compareResult.status === comparison_status_enum_1.ComparisonStatus.NOT_EXIST) {
result = await commandService.publishAsync(mappedData, options);
// 4. Finalize the import status as COMPLETED
await this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.PROCESSING, { result: result });
this.logger.log(`Successfully completed import job: ${importKey.pk}#${importKey.sk}`);
}
else {
result = await commandService.publishPartialUpdateAsync(mappedData, options);
await this.importService.updateStatus(importKey, import_status_enum_1.ImportStatusEnum.PROCESSING, { result: result });
}
}
};
exports.ImportQueueEventHandler = ImportQueueEventHandler;
exports.ImportQueueEventHandler = ImportQueueEventHandler = ImportQueueEventHandler_1 = __decorate([
(0, core_1.EventHandler)(import_queue_event_1.ImportQueueEvent),
__param(1, (0, common_1.Inject)(import_module_definition_1.PROCESS_STRATEGY_MAP)),
__metadata("design:paramtypes", [import_service_1.ImportService,
Map])
], ImportQueueEventHandler);
//# sourceMappingURL=import.queue.event.handler.js.map