1
0
Fork 0

data-less subscriber type

main v0.24.2
Jordan Hotmann 2024-09-19 12:11:08 -06:00
parent 690a0718a8
commit 1128814e2a
No known key found for this signature in database
GPG Key ID: 01B504170C2A2EA3
1 changed files with 22 additions and 0 deletions

View File

@ -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
}
})
}