Skip to content

Commit abb87c9

Browse files
authored
Add CommandEventMarshalerDecorator (#610)
* Add CommandEventMarshalerDecorator A common operation is adding some metadata to the message during marshaling. A universal decorator makes it easier than writing one from scratch.
1 parent 9bab0b1 commit abb87c9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎components/cqrs/marshaler.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package cqrs
22

33
import (
4+
"errors"
5+
"fmt"
6+
47
"github.com/ThreeDotsLabs/watermill/message"
58
)
69

@@ -23,3 +26,30 @@ type CommandEventMarshaler interface {
2326
// we should use NameFromMessage instead of Name to avoid unnecessary unmarshaling.
2427
NameFromMessage(msg *message.Message) string
2528
}
29+
30+
// CommandEventMarshalerDecorator decorates CommandEventMarshaler with additional functionality.
31+
// It can be used to add additional metadata to the message.
32+
type CommandEventMarshalerDecorator struct {
33+
CommandEventMarshaler
34+
35+
// DecorateFunc is called after marshaling the message.
36+
DecorateFunc func(v any, msg *message.Message) error
37+
}
38+
39+
// Marshal marshals Command or Event to Watermill's message and decorates it.
40+
func (c CommandEventMarshalerDecorator) Marshal(v any) (*message.Message, error) {
41+
msg, err := c.CommandEventMarshaler.Marshal(v)
42+
if err != nil {
43+
return nil, err
44+
}
45+
46+
if c.DecorateFunc == nil {
47+
return nil, errors.New("DecorateFunc is nil")
48+
}
49+
50+
if err := c.DecorateFunc(v, msg); err != nil {
51+
return nil, fmt.Errorf("cannot decorate message: %w", err)
52+
}
53+
54+
return msg, nil
55+
}

0 commit comments

Comments
 (0)