linstrom/storage/cache.go

48 lines
1.2 KiB
Go
Raw Normal View History

2024-09-12 06:56:57 +00:00
package storage
import (
"errors"
"strings"
"github.com/redis/go-redis/v9"
)
const (
cacheUserHandleToIdPrefix = "acc-name-to-id:"
cacheUserIdToAccPrefix = "acc-id-to-data:"
)
var errCacheNotFound = errors.New("not found in cache")
// Find an account id in cache using a given user handle
func (s *Storage) cacheHandleToAccUid(handle string) (*string, error) {
// Where to put the data (in case it's found)
var target string
found, err := s.cache.Get(cacheUserHandleToIdPrefix+strings.TrimLeft(handle, "@"), &target)
// If nothing was found, check error
if !found {
// Case error is set and NOT redis' error for nothing found: Return that error
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
} else {
// Else return errCacheNotFound
return nil, errCacheNotFound
}
}
return &target, nil
}
// Find an account's data in cache using a given account id
func (s *Storage) cacheAccIdToData(id string) (*Account, error) {
var target Account
found, err := s.cache.Get(cacheUserIdToAccPrefix+id, &target)
if !found {
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
} else {
return nil, errCacheNotFound
}
}
return &target, nil
}