event-store-adapter-js
v2.2.55-snapshot.1
Published
This library is designed to turn DynamoDB into an Event Store for Event Sourcing.
Downloads
6,226
Maintainers
Readme
event-store-adapter-js
This library is designed to turn DynamoDB into an Event Store for CQRS/Event Sourcing.
Installation
$ npm install event-store-adapter-js
Usage
You can easily implement an Event Sourcing-enabled repository using EventStore.
class UserAccountRepository {
constructor(
private readonly eventStore: EventStore<
UserAccountId,
UserAccount,
UserAccountEvent
>,
) {}
async storeEvent(event: UserAccountEvent, version: number) {
await this.eventStore.persistEvent(event, version);
}
async storeEventAndSnapshot(event: UserAccountEvent, snapshot: UserAccount) {
await this.eventStore.persistEventAndSnapshot(event, snapshot);
}
async findById(id: UserAccountId): Promise<UserAccount | undefined> {
const snapshot = await this.eventStore.getLatestSnapshotById(
id,
convertJSONToUserAccount,
);
if (snapshot === undefined) {
return undefined;
} else {
const events = await this.eventStore.getEventsByIdSinceSequenceNumber(
id,
snapshot.sequenceNumber + 1,
convertJSONtoUserAccountEvent,
);
return UserAccount.replay(events, snapshot);
}
}
}
The following is an example of the repository usage.
const eventStore = EventStoreFactory.ofDynamoDB<
UserAccountId,
UserAccount,
UserAccountEvent
>(
dynamodbClient,
JOURNAL_TABLE_NAME,
SNAPSHOT_TABLE_NAME,
JOURNAL_AID_INDEX_NAME,
SNAPSHOTS_AID_INDEX_NAME,
32,
convertJSONtoUserAccountEvent,
convertJSONToUserAccount,
);
// if you want to use in-memory event store, use the following code.
// const eventStore = EventStoreFactory.ofMemory<UserAccountId, UserAccount, UserAccountEvent>();
const userAccountRepository = new UserAccountRepository(eventStore);
const id = new UserAccountId(ulid());
const name = "Alice";
const [userAccount1, created] = UserAccount.create(id, name);
await userAccountRepository.storeEventAndSnapshot(created, userAccount1);
const [userAccount2, renamed] = userAccount1.rename("Bob");
await userAccountRepository.storeEvent(renamed, userAccount2.version);
const userAccount3 = await userAccountRepository.findById(id);
if (userAccount3 === undefined) {
throw new Error("userAccount3 is undefined");
}
expect(userAccount3.id).toEqual(id);
expect(userAccount3.name).toEqual("Bob");
expect(userAccount3.sequenceNumber).toEqual(2);
expect(userAccount3.version).toEqual(2);
Table Specifications
CQRS/Event Sourcing Example
See j5ik2o/cqrs-es-example-js.
License.
MIT License. See LICENSE for details.