Skip to content

Commit

Permalink
fix(manager): rework refresh to run only when necessary (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
nobe4 authored Jul 19, 2024
1 parent 839427a commit e978b48
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions internal/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,35 +53,20 @@ func (m *Manager) setRefresh(refresh, noRefresh bool) {
}

func (m *Manager) Load() error {
allNotifications := notifications.Notifications{}
m.Notifications = notifications.Notifications{}

cachedNotifications, expired, err := m.loadCache()
if err != nil {
slog.Warn("cannot read the cache: %#v\n", err)
} else if cachedNotifications != nil {
allNotifications = cachedNotifications
m.Notifications = cachedNotifications
}

if m.shouldRefresh(expired) {
fmt.Printf("Refreshing the cache...\n")

remoteNotifications, err := m.client.Notifications()
if err != nil {
return err
}

allNotifications = notifications.Sync(allNotifications, remoteNotifications)

if err := m.cache.Write(allNotifications); err != nil {
slog.Error("Error while writing the cache: %#v", err)
}
return m.refreshNotifications()
}

m.Notifications = allNotifications.Uniq()

m.Notifications, err = m.client.Enrich(m.Notifications)

return err
return nil
}

func (m *Manager) shouldRefresh(expired bool) bool {
Expand All @@ -99,6 +84,27 @@ func (m *Manager) shouldRefresh(expired bool) bool {
return expired
}

func (m *Manager) refreshNotifications() error {
fmt.Printf("Refreshing the cache...\n")

remoteNotifications, err := m.client.Notifications()
if err != nil {
return err
}

m.Notifications = notifications.Sync(m.Notifications, remoteNotifications)

if err := m.cache.Write(m.Notifications); err != nil {
slog.Error("Error while writing the cache: %#v", err)
}

m.Notifications = m.Notifications.Uniq()

m.Notifications, err = m.client.Enrich(m.Notifications)

return err
}

func (m *Manager) Save() error {
return m.cache.Write(m.Notifications.Compact())
}
Expand Down

0 comments on commit e978b48

Please sign in to comment.