@setu-ts/cqrs-plugin
v0.11.0
Published
Command and query buses with a composable pipeline of behaviors
Readme
@setu-ts/cqrs-plugin
Command Query Responsibility Segregation. Registers an ICqrsFacade under CAPABILITIES.CQRS
('cqrs'), exposing a commandBus and a queryBus.
Both buses share one request pipeline, so a behavior registered once applies to commands and queries alike.
Installation
import { CqrsPlugin } from '@setu-ts/cqrs-plugin';Usage
import { CqrsPlugin } from '@setu-ts/cqrs-plugin';
import {
CAPABILITIES,
type CqrsCommand,
type CqrsQuery,
type ICqrsFacade,
type IPipelineBehavior,
} from '@setu-ts/common';
const timing: IPipelineBehavior = {
async handle(request, next) {
const started = runtime.hrtime();
const result = await next();
logger.debug('handled', { type: request.type, ms: runtime.hrtime() - started });
return result;
},
};
app.register(CqrsPlugin({ behaviors: [timing] }));
const cqrs = app.services.get<ICqrsFacade>(CAPABILITIES.CQRS);
cqrs.commandBus.register('CreateUser', {
handle: (command: CqrsCommand<{ email: string }>) => ({ id: '123', name: 'Ada' }),
});
cqrs.queryBus.register('GetUser', {
handle: (query: CqrsQuery<{ id: string }>) => ({ id: query.data.id, name: 'Ada' }),
});
await cqrs.commandBus.execute({ type: 'CreateUser', data: { email: '[email protected]' } });
const user = await cqrs.queryBus.execute<User>({ type: 'GetUser', data: { id: '123' } });Options
| Option | Type | Default | Description |
| ----------- | --------------------- | ------- | ------------------------------------------------------ |
| behaviors | IPipelineBehavior[] | [] | Applied to every command and query, in declared order. |
A behavior that returns without calling next() short-circuits the pipeline — the handler and
all later behaviors do not run.
Errors
HandlerNotFoundError is exported for instanceof handling; it is thrown when a request reaches a
bus with no registered handler.
Exports
| Export | Kind |
| ---------------------------- | --------- |
| CqrsPlugin | function |
| CommandBus | class |
| HandlerNotFoundError | class |
| QueryBus | class |
| CommandHandlerRegistration | interface |
| CqrsCommand | interface |
| CqrsPluginOptions | interface |
| CqrsQuery | interface |
| CqrsRequest | interface |
| ICommandBus | interface |
| ICommandHandler | interface |
| ICqrsFacade | interface |
| IPipelineBehavior | interface |
| IQueryBus | interface |
| IQueryHandler | interface |
| QueryHandlerRegistration | interface |
Generated from the package barrel by pnpm run docs:exports; pnpm run check:docs fails when it
drifts.
Full API
Every export and option is documented in PUBLIC_API.md.
