Event Sourcing Framework in MongoDB
$ yarn add mongodb eventive
type MyDomainEvent =
| BaseDomainEvent<
"init",
{
// ...
}
>
| BaseDomainEvent<
"update",
{
// ...
}
>;
type MyState = {
// ...
};
import { BaseReducer } from "eventive";
const reducer: BaseReducer<MyDomainEvent, MyState> = (prevState, event) => {
// ...
return nextState;
};
import { BaseMapper } from "eventive";
const mapper: BaseMapper<MyDomainEvent> = (event) => {
// ...
return currentRevisionEvent;
};
import { eventive } from "eventive";
import { MongoClient } from "mongodb";
const mongoClient = new MongoClient();
const db = mongoClient.db("my_database");
const myRepository = eventive({
db,
entityName: "MyModel",
reducer,
mapper,
dbCollectionName: "events", // optional
});
/**
* Scan all entities
*/
myRepository.all();
/**
* Find one entity with `entityId`
*/
myRepository.findOne({
entityId: "...",
});
/**
* Find many entities with `entityIds`
*/
myRepository.batchGet({
entityIds: ["...", "..."],
});
/**
* Create entity with initial DomainEvent
*/
const { commit } = myRepository.create({
eventName: "init",
eventBody: {
// ...
},
});
/**
* Dispatch DomainEvent to entity
*/
const { commit } = myRepository.dispatch({
entity,
eventName: "edit",
eventBody: {
// ...
},
});