From e978b48d0c4ad19e32f51850d2639192e3abfabf Mon Sep 17 00:00:00 2001 From: nobe4 Date: Fri, 19 Jul 2024 19:46:36 +0200 Subject: [PATCH] fix(manager): rework refresh to run only when necessary (#100) --- internal/manager/manager.go | 44 +++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/internal/manager/manager.go b/internal/manager/manager.go index faff6c5..681b3e9 100644 --- a/internal/manager/manager.go +++ b/internal/manager/manager.go @@ -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 { @@ -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()) }