Skip to content

Commit

Permalink
feat(watermill): add sonic marshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofnds committed Dec 28, 2024
1 parent 6db86ed commit cde9ca6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
40 changes: 40 additions & 0 deletions adapter/watermill/marshaler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package watermill

import (
"github.com/ThreeDotsLabs/watermill/components/cqrs"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/bytedance/sonic"
"github.com/google/uuid"
)

var _ cqrs.CommandEventMarshaler = SonicMarshaler{}

type SonicMarshaler struct{}

func NewSonicMarshaler() SonicMarshaler {
return SonicMarshaler{}
}

func (m SonicMarshaler) Marshal(v interface{}) (*message.Message, error) {
b, err := sonic.Marshal(v)
if err != nil {
return nil, err
}

msg := message.NewMessage(uuid.NewString(), b)
msg.Metadata.Set("name", m.Name(v))

return msg, nil
}

func (SonicMarshaler) Unmarshal(msg *message.Message, v interface{}) (err error) {
return sonic.Unmarshal(msg.Payload, v)
}

func (m SonicMarshaler) Name(cmdOrEvent interface{}) string {
return cqrs.FullyQualifiedStructName(cmdOrEvent)
}

func (m SonicMarshaler) NameFromMessage(msg *message.Message) string {
return msg.Metadata.Get("name")
}
7 changes: 2 additions & 5 deletions adapter/watermill/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ var (

Providers = fx.Options(
fx.Provide(newLogger, fx.Private),
fx.Provide(newMarshaler, fx.Private),
fx.Provide(NewSonicMarshaler, fx.Private),
fx.Provide(newRouter, fx.Private),
fx.Provide(newGoChannel, fx.Private),
fx.Provide(func(m SonicMarshaler) cqrs.CommandEventMarshaler { return m }, fx.Private),
fx.Provide(func(c *gochannel.GoChannel) message.Publisher { return c }, fx.Private),
fx.Provide(func(c *gochannel.GoChannel) message.Subscriber { return c }, fx.Private),

Expand All @@ -36,10 +37,6 @@ var (
)
)

func newMarshaler() cqrs.CommandEventMarshaler {
return cqrs.JSONMarshaler{}
}

func newGoChannel(logger watermill.LoggerAdapter) *gochannel.GoChannel {
return gochannel.NewGoChannel(gochannel.Config{}, logger)
}
Expand Down

0 comments on commit cde9ca6

Please sign in to comment.