【发布时间】:2025-11-27 10:05:02
【问题描述】:
你好,我有一个命令总线,一个查询总线,它基本上有一个带有命令或查询名称和处理程序的密钥对,然后我执行应该发布我的事件的命令。 但我对如何做我的事件总线有些怀疑。 命令总线是事件总线的一部分吗? 我怎么能用处理程序做一个事件总线
命令总线:
export interface ICommand {
}
export interface ICommandHandler<
TCommand extends ICommand = any,
TResult = any
> {
execute(command: TCommand): Promise<TResult>
}
export interface ICommandBus<CommandBase extends ICommand = ICommand> {
execute<T extends CommandBase>(command: T): Promise<any>
register(data:{commandHandler: ICommandHandler, command: ICommand}[]): void
}
命令总线实现:
export class CommandBus<Command extends ICommand = ICommand>
implements ICommandBus<Command> {
private handlers = new Map<string, ICommandHandler<Command>>()
public execute<T extends Command>(command: T): Promise<any> {
const commandName = this.getCommandName(command as any)
const handler = this.handlers.get(commandName)
if (!handler) throw new Error(``)
return handler.execute(command)
}
public register(
data: { commandHandler: ICommandHandler; command: ICommand }[],
): void {
data.forEach(({command,commandHandler}) => {
this.bind(commandHandler, this.getCommandName(command as any))
})
}
private bind<T extends Command>(handler: ICommandHandler<T>, name: string) {
this.handlers.set(name, handler)
}
private getCommandName(command: Function): string {
const { constructor } = Object.getPrototypeOf(command)
return constructor.name as string
}
}
这里出现了另一个问题,谁应该负责在我的事件数据库中发布事件或读取我的事件数据库的流是我的类事件存储?
事件存储类:
export class EventStoreClient {
[x: string]: any;
/**
* @constructor
*/
constructor(private readonly config: TCPConfig) {
this.type = 'event-store';
this.eventFactory = new EventFactory();
this.connect();
}
connect() {
this.client = new TCPClient(this.config);
return this;
}
getClient() {
return this.client;
}
newEvent(name: any, payload: any) {
return this.eventFactory.newEvent(name, payload);
}
close() {
this.client.close();
return this;
}
}
然后我对如何使用我的事件处理程序和我的事件来实现我的事件总线有疑问。
如果有人可以帮助我,我会很高兴..
事件接口:
export interface IEvent {
readonly aggregrateVersion: number
readonly aggregateId: string
}
export interface IEventHandler<T extends IEvent = any> {
handle(event: T): any
}
也许用法:
commandBus.execute(new Command())
class commandHandler {
constructor(repository: IRepository, eventBus ????){}
execute(){
//how i can publish an event with after command handler logic with event bus her
}
}
【问题讨论】:
标签: node.js typescript event-sourcing event-bus eventstoredb