smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
77 lines (76 loc) • 2.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateStoreFactory = exports.InMemoryStateStore = void 0;
/**
* In-memory implementation of StateStore
* @template T Type of the data in the context
*/
class InMemoryStateStore {
constructor() {
this.store = new Map();
}
/**
* Saves a Saga context
* @param sagaId ID of the Saga
* @param context Saga context to save
*/
async save(sagaId, context) {
this.store.set(sagaId, { ...context });
}
/**
* Loads a Saga context
* @param sagaId ID of the Saga
*/
async load(sagaId) {
const context = this.store.get(sagaId);
return context ? { ...context } : null;
}
/**
* Updates a Saga context
* @param sagaId ID of the Saga
* @param context Partial Saga context to update
*/
async update(sagaId, context) {
const existingContext = this.store.get(sagaId);
if (existingContext) {
this.store.set(sagaId, {
...existingContext,
...context,
data: {
...existingContext.data,
...(context.data || {}),
},
});
}
}
/**
* Deletes a Saga context
* @param sagaId ID of the Saga
*/
async delete(sagaId) {
this.store.delete(sagaId);
}
}
exports.InMemoryStateStore = InMemoryStateStore;
/**
* Factory for creating StateStore instances
*/
class StateStoreFactory {
/**
* Creates an in-memory StateStore
* @template T Type of the data in the context
*/
static createInMemoryStore() {
return new InMemoryStateStore();
}
/**
* Creates a file system StateStore
* @param options Options for the file system store
* @template T Type of the data in the context
*/
static createFileSystemStore(options) {
const { FileSystemStateStore } = require("./FileSystemStateStore");
return new FileSystemStateStore(options);
}
}
exports.StateStoreFactory = StateStoreFactory;