Query Bus
The Query Bus implements the CQRS pattern for handling queries. Queries are read operations that return data without modifying state.
Example: User Profile Query
import {
Query,
QueryBus,
type QueryHandlerInterface,
type QueryResult,
} from "@dxbox/use-less-react/classes";
// Define query payload and result
interface GetUserProfilePayload {
userId: string;
}
interface UserProfileResult {
id: string;
fullName: string;
email: string;
avatarUrl: string;
lastActivity: Date;
}
// Create query class
class GetUserProfileQuery extends Query<
"GetUserProfile",
GetUserProfilePayload,
UserProfileResult | null
> {
get type(): "GetUserProfile" {
return "GetUserProfile";
}
}
// Define query handler
class GetUserProfileHandler
implements QueryHandlerInterface<GetUserProfileQuery>
{
async handle(
query: GetUserProfileQuery,
): Promise<QueryResult<GetUserProfileQuery>> {
const { userId } = query.payload;
// Fetch data (e.g., from database or cache)
const user = await this.userRepository.findById(userId);
if (!user) {
return null;
}
return {
id: user.id,
fullName: `${user.firstName} ${user.lastName}`,
email: user.email,
avatarUrl: user.avatarUrl,
lastActivity: user.lastActivity,
};
}
constructor(private userRepository: UserRepository) {}
}
// Setup query bus
const queryBus = new QueryBus({
monitoringService: myMonitoringService,
});
// Register handler
queryBus.registerHandler(
"GetUserProfile",
new GetUserProfileHandler(userRepository),
);
// Dispatch query
const query = new GetUserProfileQuery({ userId: "user-123" });
const result = await queryBus.dispatch(query);
if (result) {
console.log(result.fullName); // TypeScript knows the result type
}
API
QueryBus
registerHandler<T>(queryType: T["type"], handler: QueryHandlerInterface<T>): void- Register a handler for a query typedispatch<TQuery>(query: TQuery): Promise<QueryResult<TQuery>>- Dispatch a query and return typed result
Query
id: string- Unique query identifiertimestamp: Date- Query creation timestamptype: TType- Query type (must be implemented by subclass)payload: TPayload- Query payload data__resultType!: TResult- Type marker for result type inference
QueryHandlerInterface
handle(query: TQuery): Promise<QueryResult<TQuery>>- Handle the query and return typed result