goweb/cqrs/dispatcher.go

93 lines
1.8 KiB
Go
Raw Normal View History

2020-04-16 16:32:02 +02:00
package cqrs
import (
"context"
)
2020-07-07 08:19:15 +02:00
type Dispatcher struct {
2020-04-16 16:32:02 +02:00
reg *Registry
cmdFactory CommandFactory
cmdResultFactory CommandResultFactory
qryFactory QueryFactory
qryResultFactory QueryResultFactory
}
2020-07-07 08:19:15 +02:00
func (d *Dispatcher) Exec(ctx context.Context, req CommandRequest) (CommandResult, error) {
cmd, err := d.cmdFactory(req)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
2020-07-07 08:19:15 +02:00
hdlr, mdlwrs, err := d.reg.MatchCommand(cmd)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
if len(mdlwrs) > 0 {
for i := len(mdlwrs) - 1; i >= 0; i-- {
hdlr = mdlwrs[i](hdlr)
}
}
if err := hdlr.Handle(ctx, cmd); err != nil {
return nil, err
}
2020-07-07 08:19:15 +02:00
result, err := d.cmdResultFactory(cmd)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
return result, nil
}
2020-07-07 08:19:15 +02:00
func (d *Dispatcher) Query(ctx context.Context, req QueryRequest) (QueryResult, error) {
qry, err := d.qryFactory(req)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
2020-07-07 08:19:15 +02:00
hdlr, mdlwrs, err := d.reg.MatchQuery(qry)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
if len(mdlwrs) > 0 {
for i := len(mdlwrs) - 1; i >= 0; i-- {
hdlr = mdlwrs[i](hdlr)
}
}
data, err := hdlr.Handle(ctx, qry)
if err != nil {
return nil, err
}
2020-07-07 08:19:15 +02:00
result, err := d.qryResultFactory(qry, data)
2020-04-16 16:32:02 +02:00
if err != nil {
return nil, err
}
return result, nil
}
2020-07-07 08:19:15 +02:00
func (d *Dispatcher) RegisterCommand(match MatchFunc, hdlr CommandHandler, mdlwrs ...CommandMiddleware) {
d.reg.RegisterCommand(match, hdlr, mdlwrs...)
2020-04-16 16:32:02 +02:00
}
2020-07-07 08:19:15 +02:00
func (d *Dispatcher) RegisterQuery(match MatchFunc, hdlr QueryHandler, mdlwrs ...QueryMiddleware) {
d.reg.RegisterQuery(match, hdlr, mdlwrs...)
2020-04-16 16:32:02 +02:00
}
2020-07-07 08:19:15 +02:00
func NewDispatcher(funcs ...OptionFunc) *Dispatcher {
2020-04-16 16:32:02 +02:00
opt := CreateOption(funcs...)
2020-07-07 08:19:15 +02:00
return &Dispatcher{
2020-04-16 16:32:02 +02:00
reg: NewRegistry(),
cmdFactory: opt.CommandFactory,
cmdResultFactory: opt.CommandResultFactory,
qryFactory: opt.QueryFactory,
qryResultFactory: opt.QueryResultFactory,
}
}