github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/components/cqrs/event_handler.go (about) 1 package cqrs 2 3 import ( 4 "context" 5 ) 6 7 // EventHandler receives events defined by NewEvent and handles them with its Handle method. 8 // If using DDD, CommandHandler may modify and persist the aggregate. 9 // It can also invoke a process manager, a saga or just build a read model. 10 // 11 // In contrast to CommandHandler, every Event can have multiple EventHandlers. 12 // 13 // One instance of EventHandler is used during handling messages. 14 // When multiple events are delivered at the same time, Handle method can be executed multiple times at the same time. 15 // Because of that, Handle method needs to be thread safe! 16 type EventHandler interface { 17 // HandlerName is the name used in message.Router while creating handler. 18 // 19 // It will be also passed to EventsSubscriberConstructor. 20 // May be useful, for example, to create a consumer group per each handler. 21 // 22 // WARNING: If HandlerName was changed and is used for generating consumer groups, 23 // it may result with **reconsuming all messages** !!! 24 HandlerName() string 25 26 NewEvent() any 27 28 Handle(ctx context.Context, event any) error 29 } 30 31 type genericEventHandler[T any] struct { 32 handleFunc func(ctx context.Context, event *T) error 33 handlerName string 34 } 35 36 // NewEventHandler creates a new EventHandler implementation based on provided function 37 // and event type inferred from function argument. 38 func NewEventHandler[T any]( 39 handlerName string, 40 handleFunc func(ctx context.Context, event *T) error, 41 ) EventHandler { 42 return &genericEventHandler[T]{ 43 handleFunc: handleFunc, 44 handlerName: handlerName, 45 } 46 } 47 48 func (c genericEventHandler[T]) HandlerName() string { 49 return c.handlerName 50 } 51 52 func (c genericEventHandler[T]) NewEvent() any { 53 tVar := new(T) 54 return tVar 55 } 56 57 func (c genericEventHandler[T]) Handle(ctx context.Context, e any) error { 58 event := e.(*T) 59 return c.handleFunc(ctx, event) 60 } 61 62 type GroupEventHandler interface { 63 NewEvent() any 64 Handle(ctx context.Context, event any) error 65 } 66 67 // NewGroupEventHandler creates a new GroupEventHandler implementation based on provided function 68 // and event type inferred from function argument. 69 func NewGroupEventHandler[T any](handleFunc func(ctx context.Context, event *T) error) GroupEventHandler { 70 return &genericEventHandler[T]{ 71 handleFunc: handleFunc, 72 } 73 }