Skip to content

Commit

Permalink
Added helpers for commands/queries bus
Browse files Browse the repository at this point in the history
  • Loading branch information
theskyinflames-macos authored and theskyinflames-macos committed Dec 9, 2022
1 parent b17e036 commit 96b49d5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
14 changes: 2 additions & 12 deletions examples/command_bus/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package main

import (
"context"
"errors"
"fmt"
"time"

"github.com/theskyinflames/cqrs-eda/pkg/bus"
"github.com/theskyinflames/cqrs-eda/pkg/cqrs"
"github.com/theskyinflames/cqrs-eda/pkg/helpers"

"github.com/google/uuid"
)
Expand Down Expand Up @@ -40,7 +40,7 @@ func (ch AddUserCommandHandler) Handle(ctx context.Context, cmd cqrs.Command) ([

func main() {
bus := bus.New()
bus.Register(addUserCommandName, busHandler(AddUserCommandHandler{}))
bus.Register(addUserCommandName, helpers.BusChHandler(AddUserCommandHandler{}))

cmd := AddUserCommand{
ID: uuid.New(),
Expand All @@ -54,13 +54,3 @@ func main() {
// Give time to output traces
time.Sleep(time.Second)
}

func busHandler(ch cqrs.CommandHandler) bus.Handler {
return func(ctx context.Context, d bus.Dispatchable) (any, error) {
cmd, ok := d.(cqrs.Command)
if !ok {
return nil, errors.New("unexpected dispatchable")
}
return ch.Handle(ctx, cmd)
}
}
29 changes: 29 additions & 0 deletions pkg/helpers/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package helpers

import (
"context"
"errors"

"github.com/theskyinflames/cqrs-eda/pkg/bus"
"github.com/theskyinflames/cqrs-eda/pkg/cqrs"
)

func BusChHandler(ch cqrs.CommandHandler) bus.Handler {
return func(ctx context.Context, d bus.Dispatchable) (any, error) {
cmd, ok := d.(cqrs.Command)
if !ok {
return nil, errors.New("unexpected dispatchable")
}
return ch.Handle(ctx, cmd)
}
}

func BusQhHandler(ch cqrs.QueryHandler) bus.Handler {
return func(ctx context.Context, d bus.Dispatchable) (any, error) {
cmd, ok := d.(cqrs.Query)
if !ok {
return nil, errors.New("unexpected dispatchable")
}
return ch.Handle(ctx, cmd)
}
}

0 comments on commit 96b49d5

Please sign in to comment.