Sorci.js
    Preparing search index...

    Function getAggregateByQueryFactory

    • Factory function to create a typed aggregate getter for an EventMap.

      Type Parameters

      • TEventMap

      Parameters

      • getEventsByQuery: (query: Query) => Promise<PersistedEvent[]>

        Function to fetch events from the event store

      Returns <TQuery extends Query>(
          query: TQuery,
          reducer: (
              state: DeepPrettify<
                  MergeProperties<UnionData<TEventMap, ExtractTypes<TQuery>>>,
              >,
              event: PersistedEvent,
          ) => DeepPrettify<
              MergeProperties<UnionData<TEventMap, ExtractTypes<TQuery>>>,
          >,
      ) => Promise<
          {
              query: TQuery;
              state: DeepPrettify<
                  MergeProperties<UnionData<TEventMap, ExtractTypes<TQuery>>>,
              >;
          },
      >

      A typed function that builds aggregates from query results

      type TodoListEventMap = {
      "todo-list-created": { todoListId: string; title: string };
      "todo-list-renamed": { title: string; renamedCount: number };
      };

      const getAggregate = getAggregateByQueryFactory<TodoListEventMap>(
      (query) => sorci.getEventsByQuery(query)
      );

      const query = {
      $where: {
      type: { $in: ["todo-list-created", "todo-list-renamed"] as const }
      }
      };

      const result = await getAggregate(query, (state, event) => {
      return { ...state, ...event.data };
      });

      // result.state is typed as: { todoListId: string; title: string; renamedCount: number }
      // result.query is the original query with full type information