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.
24 lines
562 B
Go
24 lines
562 B
Go
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)
|
|
})
|
|
}
|