Skip to content

Commit

Permalink
Make NewMessageCounter async
Browse files Browse the repository at this point in the history
  • Loading branch information
nagaeki committed Jun 24, 2024
1 parent 4ac1640 commit 56f861a
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions service/counter/message.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package counter

import (
"fmt"
//"fmt"
"sync"

"github.com/leandro-lugaresi/hub"
Expand Down Expand Up @@ -34,10 +34,14 @@ type messageCounterImpl struct {
// NewMessageCounter 全メッセージ数カウンタを生成します
func NewMessageCounter(db *gorm.DB, hub *hub.Hub) (MessageCounter, error) {
counter := &messageCounterImpl{}
if err := db.Unscoped().Model(&model.Message{}).Count(&counter.count).Error; err != nil {
return nil, fmt.Errorf("failed to load total messages count: %w", err)
}
messagesCounter.Add(float64(counter.count))

go func() {
if err := db.Unscoped().Model(&model.Message{}).Count(&counter.count).Error; err != nil {
panic(err)
}
messagesCounter.Add(float64(counter.count))
}()

go func() {
for range hub.Subscribe(1, event.MessageCreated).Receiver {
counter.inc()
Expand Down

0 comments on commit 56f861a

Please sign in to comment.