feat: encapsulate snapshot

This commit is contained in:
2025-08-11 14:04:38 +02:00
parent 91c3755533
commit 6da78b043d
4 changed files with 118 additions and 103 deletions

View File

@@ -153,7 +153,7 @@ export abstract class AggregateRoot<TEventFactory extends EventFactory> {
} }
await this.save(); await this.save();
const reducer = this.#store.aggregate.reducer(this.#self); const reducer = this.#store.aggregate.reducer(this.#self);
await this.#store.createSnapshot({ await this.#store.snapshot.create({
name: this.#self.name, name: this.#self.name,
stream, stream,
reducer, reducer,

View File

@@ -121,6 +121,14 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* *
* @param aggregates - Aggregates to push events from. * @param aggregates - Aggregates to push events from.
* @param settings - Event settings which can modify insertion behavior. * @param settings - Event settings which can modify insertion behavior.
*
* @example
* ```ts
* const foo = eventStore.aggregate.from(Foo).setEvent(...);
* const bar = eventStore.aggregate.from(Bar).setEvent(...);
*
* await eventStore.aggregate.push([foo, bar]);
* ```
*/ */
push: async ( push: async (
aggregates: InstanceType<AggregateRootClass<TEventFactory>>[], aggregates: InstanceType<AggregateRootClass<TEventFactory>>[],
@@ -141,6 +149,11 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* *
* @param name - Aggregate to instantiate. * @param name - Aggregate to instantiate.
* @param stream - Stream to retrieve snapshot from. * @param stream - Stream to retrieve snapshot from.
*
* @example
* ```ts
* const state = await eventStore.aggregate.getByStream(Aggregate, "stream");
* ```
*/ */
getByStream: async <TAggregate extends AggregateRootClass<TEventFactory>>( getByStream: async <TAggregate extends AggregateRootClass<TEventFactory>>(
aggregate: TAggregate, aggregate: TAggregate,
@@ -159,6 +172,11 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* *
* @param name - Aggregate to instantiate. * @param name - Aggregate to instantiate.
* @param relation - Relation to retrieve snapshot from. * @param relation - Relation to retrieve snapshot from.
*
* @example
* ```ts
* const state = await eventStore.aggregate.getByRelation(Aggregate, "relation");
* ```
*/ */
getByRelation: async <TAggregate extends AggregateRootClass<TEventFactory>>( getByRelation: async <TAggregate extends AggregateRootClass<TEventFactory>>(
aggregate: TAggregate, aggregate: TAggregate,
@@ -177,6 +195,11 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* *
* @param aggregate - Aggregate to instantiate. * @param aggregate - Aggregate to instantiate.
* @param snapshot - Optional snapshot to instantiate aggregate with. * @param snapshot - Optional snapshot to instantiate aggregate with.
*
* @example
* ```ts
* const foo = await eventStore.aggregate.from(Foo);
* ```
*/ */
from: <TAggregate extends AggregateRootClass<TEventFactory>>( from: <TAggregate extends AggregateRootClass<TEventFactory>>(
aggregate: TAggregate, aggregate: TAggregate,
@@ -189,6 +212,12 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* Create a new reducer instance for the given aggregate. * Create a new reducer instance for the given aggregate.
* *
* @param aggregate - Aggregate to create a reducer for. * @param aggregate - Aggregate to create a reducer for.
*
* @example
* ```ts
* const reducer = eventStore.aggregate.reducer(Aggregate);
* const state = await eventStore.reduce({ name: "foo:reducer", stream: "stream-id", reducer });
* ```
*/ */
reducer: <TAggregate extends AggregateRootClass<TEventFactory>>( reducer: <TAggregate extends AggregateRootClass<TEventFactory>>(
aggregate: TAggregate, aggregate: TAggregate,
@@ -382,18 +411,11 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* @param pending - List of non comitted events to append to the server events. * @param pending - List of non comitted events to append to the server events.
* *
* @example * @example
*
* ```ts * ```ts
* const reducer = eventStore.aggregate.reducer(Aggregate);
* const state = await eventStore.reduce({ stream, reducer }); * const state = await eventStore.reduce({ stream, reducer });
* ```
*
* @example
*
* ```ts
* const state = await eventStore.reduce({ relation: `foo:${foo}:bars`, reducer }); * const state = await eventStore.reduce({ relation: `foo:${foo}:bars`, reducer });
* ``` * ```
*
* Reducers are created through the `.makeReducer` and `.makeAggregateReducer` method.
*/ */
async reduce<TReducer extends Reducer>( async reduce<TReducer extends Reducer>(
{ name, stream, relation, reducer, ...query }: ReduceQuery<TReducer>, { name, stream, relation, reducer, ...query }: ReduceQuery<TReducer>,
@@ -404,7 +426,7 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
let state: InferReducerState<TReducer> | undefined; let state: InferReducerState<TReducer> | undefined;
let cursor: string | undefined; let cursor: string | undefined;
const snapshot = await this.getSnapshot(name, id); const snapshot = await this.snapshot.get(name, id);
if (snapshot !== undefined) { if (snapshot !== undefined) {
cursor = snapshot.cursor; cursor = snapshot.cursor;
state = snapshot.state; state = snapshot.state;
@@ -436,6 +458,7 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
|-------------------------------------------------------------------------------- |--------------------------------------------------------------------------------
*/ */
readonly snapshot = {
/** /**
* Create a new snapshot for the given stream/relation and reducer. * Create a new snapshot for the given stream/relation and reducer.
* *
@@ -444,28 +467,26 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* @example * @example
* ```ts * ```ts
* await eventStore.createSnapshot({ stream, reducer }); * await eventStore.createSnapshot({ stream, reducer });
* ```
*
* @example
* ```ts
* await eventStore.createSnapshot({ relation: `foo:${foo}:bars`, reducer }); * await eventStore.createSnapshot({ relation: `foo:${foo}:bars`, reducer });
* ``` * ```
*/ */
async createSnapshot<TReducer extends Reducer>({ create: async <TReducer extends Reducer>({
name, name,
stream, stream,
relation, relation,
reducer, reducer,
...query ...query
}: ReduceQuery<TReducer>): Promise<void> { }: ReduceQuery<TReducer>): Promise<void> => {
const id = stream ?? relation; const id = stream ?? relation;
const events = const events =
stream !== undefined ? await this.getEventsByStreams([id], query) : await this.getEventsByRelations([id], query); stream !== undefined
? await this.getEventsByStreams([id], query)
: await this.getEventsByRelations([id], query);
if (events.length === 0) { if (events.length === 0) {
return undefined; return undefined;
} }
await this.snapshots.insert(name, id, events.at(-1)!.created, reducer.reduce(events)); await this.snapshots.insert(name, id, events.at(-1)!.created, reducer.reduce(events));
} },
/** /**
* Get an entity state snapshot from the database. These are useful for when we * Get an entity state snapshot from the database. These are useful for when we
@@ -485,10 +506,7 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* // foo: "bar" * // foo: "bar"
* // } * // }
* // } * // }
* ```
* *
* @example
* ```ts
* const snapshot = await eventStore.getSnapshot("foo:reducer", `foo:${foo}:bars`); * const snapshot = await eventStore.getSnapshot("foo:reducer", `foo:${foo}:bars`);
* console.log(snapshot); * console.log(snapshot);
* // { * // {
@@ -499,16 +517,16 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* // } * // }
* ``` * ```
*/ */
async getSnapshot<TReducer extends Reducer, TState = InferReducerState<TReducer>>( get: async <TReducer extends Reducer, TState = InferReducerState<TReducer>>(
name: string, name: string,
streamOrRelation: string, streamOrRelation: string,
): Promise<{ cursor: string; state: TState } | undefined> { ): Promise<{ cursor: string; state: TState } | undefined> => {
const snapshot = await this.snapshots.getByStream(name, streamOrRelation); const snapshot = await this.snapshots.getByStream(name, streamOrRelation);
if (snapshot === undefined) { if (snapshot === undefined) {
return undefined; return undefined;
} }
return { cursor: snapshot.cursor, state: snapshot.state as TState }; return { cursor: snapshot.cursor, state: snapshot.state as TState };
} },
/** /**
* Delete a snapshot. * Delete a snapshot.
@@ -519,16 +537,13 @@ export class EventStore<TEventFactory extends EventFactory, TEventStoreAdapter e
* @example * @example
* ```ts * ```ts
* await eventStore.deleteSnapshot("foo:reducer", stream); * await eventStore.deleteSnapshot("foo:reducer", stream);
* ```
*
* @example
* ```ts
* await eventStore.deleteSnapshot("foo:reducer", `foo:${foo}:bars`); * await eventStore.deleteSnapshot("foo:reducer", `foo:${foo}:bars`);
* ``` * ```
*/ */
async deleteSnapshot(name: string, streamOrRelation: string): Promise<void> { delete: async (name: string, streamOrRelation: string): Promise<void> => {
await this.snapshots.remove(name, streamOrRelation); await this.snapshots.remove(name, streamOrRelation);
} },
};
} }
/* /*

View File

@@ -49,7 +49,7 @@ export default describe<Events>(".createSnapshot", (getEventStore) => {
}), }),
); );
await store.createSnapshot({ name: "user", stream, reducer: userReducer }); await store.snapshot.create({ name: "user", stream, reducer: userReducer });
const snapshot = await store.snapshots.getByStream("user", stream); const snapshot = await store.snapshots.getByStream("user", stream);

View File

@@ -81,7 +81,7 @@ export default describe<Events>(".reduce", (getEventStore) => {
}), }),
); );
await store.createSnapshot({ name: "user", stream, reducer: userReducer }); await store.snapshot.create({ name: "user", stream, reducer: userReducer });
const state = await store.reduce({ name: "user", stream, reducer: userReducer }); const state = await store.reduce({ name: "user", stream, reducer: userReducer });