getanthill
Event-Source
Getting Started
Install the package
npm install -S @getanthill/event-source
Define your class
The following will be extended with the Event-Source
functionalities.
import { EventSourcedFactory } from '@getanthill/event-source';
const reducer = (state, event) => {
if (event.type === 'CREATED') {
return {
firstname: event.firstname,
};
}
return state;
};
export default class Users extends EventSourced('users', reducer) {
create(firstname) {
return this.handle(() => [
{
type: 'CREATED',
firstname,
},
]);
}
}
Use your Event-Sourced class
import Users from '../models/Users';
function createUser(db, firstname) {
const user = new Users(db, 1);
return user.create('John');
}
In your database, we will now have access to the events in the collection
users_events
:
db.users_events.find().pretty();
{
"type": "CREATED",
"correlation_id": 1,
"version": 0,
"firstname": "John",
"created_at": "2020-11-01T06:05:43.210Z"
}
and also the final resulting state of your object:
db.users.find().pretty();
{
"correlation_id": 1,
"version": 0,
"firstname": "John"
}
Conclusion
Now that you are able to have a fully Event-Source featured class, you can
read further on what is possible to create with this library and how to custom
a bit some features such as the correlation_id
naming.