Implementing usergroups caching

Signed-off-by: Ethan Wellenreiter <ewellenreiter@gmail.com>
This commit is contained in:
Ethan Wellenreiter 2025-05-07 00:00:54 -04:00
parent 064faeadca
commit 2b2fa217d6
2 changed files with 53 additions and 2 deletions

View File

@ -34,8 +34,8 @@ type Storage struct {
Delete(ctx context.Context, name string)
}
UserGroups interface {
Get(ctx context.Context, userid int64) (*[]int64, error)
Set(ctx context.Context, groups *[]int64) error
Get(ctx context.Context, userid int64) (*storage.UserGroups, error)
Set(ctx context.Context, groups *storage.UserGroups) error
Delete(ctx context.Context, userid int64)
}
Receipts interface {

View File

@ -0,0 +1,51 @@
package cache
import (
"context"
"encoding/json"
"fmt"
"git.ewellenr.ca/receipt_indexer/backend/internal/storage"
"github.com/redis/go-redis/v9"
)
type UserGroupsStore struct {
rdb *redis.Client
}
func (s *UserGroupsStore) Get(ctx context.Context, userid int64) (*storage.UserGroups, error) {
cacheKey := fmt.Sprintf("user-%d", userid)
data, err := s.rdb.Get(ctx, cacheKey).Result()
if err == redis.Nil {
return nil, nil
} else if err != nil {
return nil, err
}
var usergroups storage.UserGroups
if data != "" {
err := json.Unmarshal([]byte(data), &usergroups)
if err != nil {
return nil, err
}
}
return &usergroups, nil
}
func (s *UserGroupsStore) Set(ctx context.Context, groups *storage.UserGroups) error {
cacheKey := fmt.Sprintf("user-%d", groups.UserID)
json, err := json.Marshal(groups)
if err != nil {
return err
}
return s.rdb.Set(ctx, cacheKey, json, RolesExpTime).Err()
}
func (s *UserGroupsStore) Delete(ctx context.Context, userid int64) {
cacheKey := fmt.Sprintf("user-%d", userid)
s.rdb.Del(ctx, cacheKey)
}