feat: modular domain driven boilerplate
This commit is contained in:
54
modules/identity/event-store.ts
Normal file
54
modules/identity/event-store.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { container } from "@platform/database/container.ts";
|
||||
import { EventFactory, EventStore, Prettify, Projector } from "@valkyr/event-store";
|
||||
import { MongoAdapter } from "@valkyr/event-store/mongo";
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Event Factory
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
const eventFactory = new EventFactory([
|
||||
...(await import("./events/code.ts")).default,
|
||||
...(await import("./events/identity.ts")).default,
|
||||
]);
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Event Store
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
export const eventStore = new EventStore({
|
||||
adapter: new MongoAdapter(() => container.get("mongo"), `identity:event-store`),
|
||||
events: eventFactory,
|
||||
snapshot: "auto",
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Projector
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
export const projector = new Projector<EventStoreFactory>();
|
||||
|
||||
eventStore.onEventsInserted(async (records, { batch }) => {
|
||||
if (batch !== undefined) {
|
||||
await projector.pushMany(batch, records);
|
||||
} else {
|
||||
for (const record of records) {
|
||||
await projector.push(record, { hydrated: false, outdated: false });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------------
|
||||
| Events
|
||||
|--------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
export type EventStoreFactory = typeof eventFactory;
|
||||
|
||||
export type EventRecord = Prettify<EventStoreFactory["$events"][number]["$record"]>;
|
||||
Reference in New Issue
Block a user