This commit is contained in:
parent
2346f17edd
commit
f9d1cf744e
@ -49,22 +49,10 @@ func NewDiscogsCache(token string, maxCacheAge time.Duration, username string, p
|
||||
persistFile: persistFile,
|
||||
}
|
||||
if cache.persistence && cache.persistFile != "" {
|
||||
p := &persistence{}
|
||||
f, err := os.Open(cache.persistFile)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
log.Printf("%s not found, skipping file load...", cache.persistFile)
|
||||
return cache, nil
|
||||
}
|
||||
cache.cache, cache.lastRefresh, err = cache.loadRecordsFromFS(context.Background())
|
||||
if err != nil {
|
||||
return cache, fmt.Errorf("error opening cache file %s: %w", cache.persistFile, err)
|
||||
return nil, fmt.Errorf("cache load failed: %w", err)
|
||||
}
|
||||
err = gob.NewDecoder(f).Decode(p)
|
||||
if err != nil {
|
||||
return cache, fmt.Errorf("error readhing from cache file %s: %w", cache.persistFile, err)
|
||||
}
|
||||
log.Printf("loaded %d records from %s", len(p.CachedRecordSlice), cache.persistFile)
|
||||
cache.cache = p.CachedRecordSlice
|
||||
cache.lastRefresh = p.LastRefresh
|
||||
if time.Now().After(cache.lastRefresh.Add(cache.maxCacheAge)) {
|
||||
log.Printf("cache expired, running refresh...")
|
||||
go func() {
|
||||
@ -102,6 +90,24 @@ func (c *DiscogsCache) GetAllRecords(ctx context.Context) ([]media.Record, error
|
||||
return c.cache, nil
|
||||
}
|
||||
|
||||
func (c *DiscogsCache) loadRecordsFromFS(ctx context.Context) ([]media.Record, time.Time, error) {
|
||||
p := &persistence{}
|
||||
f, err := os.Open(c.persistFile)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
log.Printf("%s not found, skipping file load...", c.persistFile)
|
||||
return nil, time.Time{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, time.Time{}, fmt.Errorf("error opening cache file %s: %w", c.persistFile, err)
|
||||
}
|
||||
err = gob.NewDecoder(f).Decode(p)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, fmt.Errorf("error readhing from cache file %s: %w", c.persistFile, err)
|
||||
}
|
||||
log.Printf("loaded %d records from %s", len(p.CachedRecordSlice), c.persistFile)
|
||||
return p.CachedRecordSlice, p.LastRefresh, nil
|
||||
}
|
||||
|
||||
func (c *DiscogsCache) saveRecordsToCache(ctx context.Context, records []media.Record) error {
|
||||
c.cache = records
|
||||
c.lastRefresh = time.Now()
|
||||
|
Loading…
Reference in New Issue
Block a user