feat: add JetStream message replay to chatroom example

Replay stored messages from JetStream when joining or switching rooms
so users see chat history immediately.
This commit is contained in:
Ryan Hamamura
2026-01-26 08:10:30 -10:00
parent 30cc6d88e6
commit d8318af9c4

View File

@@ -146,7 +146,27 @@ func main() {
if currentSub != nil { if currentSub != nil {
currentSub.Unsubscribe() currentSub.Unsubscribe()
} }
sub, _ := c.Subscribe("chat.room."+room, func(data []byte) {
// Replay history from JetStream before subscribing for real-time
subject := "chat.room." + room
if hist, err := js.SubscribeSync(subject, nats.DeliverAll(), nats.OrderedConsumer()); err == nil {
for {
msg, err := hist.NextMsg(200 * time.Millisecond)
if err != nil {
break
}
var chatMsg ChatMessage
if json.Unmarshal(msg.Data, &chatMsg) == nil {
messages = append(messages, chatMsg)
}
}
hist.Unsubscribe()
if len(messages) > 50 {
messages = messages[len(messages)-50:]
}
}
sub, _ := c.Subscribe(subject, func(data []byte) {
var msg ChatMessage var msg ChatMessage
if err := json.Unmarshal(data, &msg); err != nil { if err := json.Unmarshal(data, &msg); err != nil {
return return