From 1128814e2a45fd77da56328fd58e6df2cd413cfa Mon Sep 17 00:00:00 2001 From: Jordan Hotmann Date: Thu, 19 Sep 2024 12:11:08 -0600 Subject: [PATCH] data-less subscriber type --- pkg/nats/subscribers.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pkg/nats/subscribers.go b/pkg/nats/subscribers.go index 9c9c9c8..ed10749 100644 --- a/pkg/nats/subscribers.go +++ b/pkg/nats/subscribers.go @@ -49,6 +49,7 @@ func parseEvent(msg *nats.Msg, sendResponse bool) (ha.EventData, error) { return data, err } +// AddEventSub: Add a subscriber to the NATS client that receives the full event payload func (n *NatsConnection) AddEventSub(t TopicType, entityId string, handler func(ha.EventData) error) (*nats.Subscription, error) { if t == "" || entityId == "" { panic("TopicType and entityId cannot be empty") @@ -73,6 +74,7 @@ func (n *NatsConnection) AddEventSub(t TopicType, entityId string, handler func( }) } +// AddStateSub: Add a subscriber to the NATS client that receives the new state payload from an event func (n *NatsConnection) AddStateSub(t TopicType, entityId string, handler func(ha.StateData) error) (*nats.Subscription, error) { if t == "" || entityId == "" { panic("TopicType and entityId cannot be empty") @@ -96,3 +98,23 @@ func (n *NatsConnection) AddStateSub(t TopicType, entityId string, handler func( } }) } + +// AddSub: Add a subscriber to the NATS client that doesn't receive any data from the event +func (n *NatsConnection) AddSub(t TopicType, entityId string, handler func() error) (*nats.Subscription, error) { + if t == "" || entityId == "" { + panic("TopicType and entityId cannot be empty") + } + + topic := t.GetTopic(entityId) + l := n.logger.With("topic", topic, "entity_id", entityId) + l.Debug("Subscribing to topic") + + return n.addSub(topic, func(msg *nats.Msg) { + l.Debug(fmt.Sprintf("%s event fired", t)) + err := handler() + if err != nil { + l.Error(fmt.Sprintf("Error handling %s event", t), "error", err) + return + } + }) +}