Bus for executing queries through their handlers.

Ensures that each query is handled by exactly one handler.

// Register handler
queryBus.register(GetUserQuery, new GetUserQueryHandler());

// Execute query
const user = await queryBus.execute<User | null>(
new GetUserQuery('user-123')
);
interface QueryBus {
    register<TQuery extends Query, TResult = unknown>(
        queryType: new (...args: unknown[]) => TQuery,
        handler: QueryHandler<TQuery, TResult>,
    ): void;
    execute<TResult = unknown>(query: Query): Promise<TResult>;
}

Methods

  • Executes a query through its registered handler.

    Type Parameters

    • TResult = unknown

      The expected result type

    Parameters

    • query: Query

      The query to execute

    Returns Promise<TResult>

    The result from the query handler

    Error if no handler is registered for the query

    const query = new GetUserQuery('user-123');
    const user = await queryBus.execute<User | null>(query);