feat: add generic pub/sub helpers and pubsub-crud example
Add typed Publish[T] and Subscribe[T] generic helpers that handle JSON marshaling, along with vianats.EnsureStream and ReplayHistory helpers. Refactor nats-chatroom to use the new APIs. Add pubsub-crud example demonstrating CRUD operations with DaisyUI toast notifications broadcast to all connected clients via NATS.
This commit is contained in:
23
pubsub_helpers.go
Normal file
23
pubsub_helpers.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package via
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Publish JSON-marshals msg and publishes to subject.
|
||||
func Publish[T any](c *Context, subject string, msg T) error {
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.Publish(subject, data)
|
||||
}
|
||||
|
||||
// Subscribe JSON-unmarshals each message as T and calls handler.
|
||||
func Subscribe[T any](c *Context, subject string, handler func(T)) (Subscription, error) {
|
||||
return c.Subscribe(subject, func(data []byte) {
|
||||
var msg T
|
||||
if err := json.Unmarshal(data, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
handler(msg)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user