diff --git a/notifications_dispatcher.go b/notifications_dispatcher.go new file mode 100644 index 0000000..22cd0e1 --- /dev/null +++ b/notifications_dispatcher.go @@ -0,0 +1,89 @@ +package walletclient + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/pkg/errors" +) + +type Handlers struct { + GeneralPurposeEvent []func(*GeneralPurposeEvent) +} + +type NotificationsDispatcher struct { + ctx context.Context + input chan *RawEvent + handlers Handlers +} + +func NewNotificationsDispatcher(ctx context.Context, inputChannel chan *RawEvent) *NotificationsDispatcher { + obj := &NotificationsDispatcher{ + ctx: ctx, + input: inputChannel, + } + + return obj +} + +func (nd *NotificationsDispatcher) process() { + for { + select { + case event := <-nd.input: + switch event.Type { + case "general-purpose-event": + content, err := GetEventContent[GeneralPurposeEvent](event) + if err != nil { + fmt.Println("Error getting event content") + continue + } + for _, handler := range nd.handlers.GeneralPurposeEvent { + handler(content) + } + } + case <-nd.ctx.Done(): + return + } + } +} + +////////////////////// BELOW it should be imported from spv-wallet models + +// RawEvent - event type +type RawEvent struct { + Type string `json:"type"` + Content json.RawMessage `json:"content"` +} + +type EventContent interface { + GetType() string +} + +type GeneralPurposeEvent struct { + Value string +} + +func (GeneralPurposeEvent) GetType() string { + return "general-purpose-event" +} + +func GetEventContent[modelType EventContent](raw *RawEvent) (*modelType, error) { + model := *new(modelType) + if raw.Type != model.GetType() { + return nil, fmt.Errorf("Wrong type") + } + + if err := json.Unmarshal(raw.Content, &model); err != nil { + return nil, errors.Wrap(err, "Cannot unmarshall the content json") + } + return &model, nil +} + +func NewRawEvent(namedEvent EventContent) *RawEvent { + asJson, _ := json.Marshal(namedEvent) + return &RawEvent{ + Type: namedEvent.GetType(), + Content: asJson, + } +} diff --git a/webhook.go b/webhook.go index e35d8ae..95c5f46 100644 --- a/webhook.go +++ b/webhook.go @@ -12,13 +12,11 @@ const ( eventBufferLength = 100 ) -type Event any - type Webhook struct { URL string TokenHeader string TokenValue string - Channel chan Event + Channel chan *RawEvent client *WalletClient } @@ -28,7 +26,7 @@ func NewWebhook(client *WalletClient, url, tokenHeader, tokenValue string) *Webh URL: url, TokenHeader: tokenHeader, TokenValue: tokenValue, - Channel: make(chan Event, eventBufferLength), + Channel: make(chan *RawEvent, eventBufferLength), client: client, } } @@ -47,7 +45,7 @@ func (w *Webhook) HTTPHandler() http.Handler { http.Error(rw, "Unauthorized", http.StatusUnauthorized) return } - var events []Event + var events []*RawEvent if err := json.NewDecoder(r.Body).Decode(&events); err != nil { http.Error(rw, err.Error(), http.StatusBadRequest) return