smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
84 lines (83 loc) • 2.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Saga = void 0;
const uuid_1 = require("uuid");
const types_1 = require("../types");
/**
* Base class for all Sagas
* @template T Type of the data in the context
*/
class Saga {
/**
* Creates a new Saga instance
* @param options Options for the Saga
*/
constructor(options = {}, initialData) {
this.id = options.id || (0, uuid_1.v4)();
this.options = {
timeout: 30000, // 30 seconds default timeout
retryCount: 3,
retryDelay: 1000,
...options,
};
this.context = {
sagaId: this.id,
data: initialData || {},
status: types_1.SagaStatus.STARTED,
startTime: Date.now(),
};
}
/**
* Gets the ID of the Saga
*/
getId() {
return this.id;
}
/**
* Gets the context of the Saga
*/
getContext() {
return { ...this.context };
}
/**
* Updates the context data of the Saga
* @param data Data to update in the context
*/
updateContext(data) {
this.context.data = {
...this.context.data,
...data,
};
}
/**
* Sets the status of the Saga
* @param status New status
* @param error Optional error message
*/
setStatus(status, error) {
this.context.status = status;
if (error) {
this.context.error = error;
}
if (status === types_1.SagaStatus.COMPLETED ||
status === types_1.SagaStatus.FAILED ||
status === types_1.SagaStatus.COMPENSATED ||
status === types_1.SagaStatus.COMPENSATION_FAILED) {
this.context.endTime = Date.now();
}
}
/**
* Checks if the Saga is completed
*/
isCompleted() {
return this.context.status === types_1.SagaStatus.COMPLETED;
}
/**
* Checks if the Saga has failed
*/
isFailed() {
return (this.context.status === types_1.SagaStatus.FAILED ||
this.context.status === types_1.SagaStatus.COMPENSATION_FAILED);
}
}
exports.Saga = Saga;