Implementing group caching
Signed-off-by: Ethan Wellenreiter <ewellenreiter@gmail.com>
This commit is contained in:
parent
2b2fa217d6
commit
d8b2bd7226
6
backend/internal/storage/cache/cache.go
vendored
6
backend/internal/storage/cache/cache.go
vendored
@ -29,9 +29,9 @@ type Storage struct {
|
||||
Delete(ctx context.Context, name string)
|
||||
}
|
||||
Groups interface {
|
||||
Get(ctx context.Context, name string) (*storage.Role, error)
|
||||
Set(ctx context.Context, role *storage.Role) error
|
||||
Delete(ctx context.Context, name string)
|
||||
Get(ctx context.Context, id int64) (*storage.Group, error)
|
||||
Set(ctx context.Context, group *storage.Group) error
|
||||
Delete(ctx context.Context, id int64)
|
||||
}
|
||||
UserGroups interface {
|
||||
Get(ctx context.Context, userid int64) (*storage.UserGroups, error)
|
||||
|
||||
55
backend/internal/storage/cache/redis_groups.go
vendored
Normal file
55
backend/internal/storage/cache/redis_groups.go
vendored
Normal file
@ -0,0 +1,55 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"git.ewellenr.ca/receipt_indexer/backend/internal/storage"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type GroupStore struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
func (s *GroupStore) generateCacheKey(id int64) string {
|
||||
return fmt.Sprintf("group-%d", id)
|
||||
}
|
||||
|
||||
func (s *GroupStore) Get(ctx context.Context, id int64) (*storage.Group, error) {
|
||||
cacheKey := s.generateCacheKey(id)
|
||||
|
||||
data, err := s.rdb.Get(ctx, cacheKey).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var group storage.Group
|
||||
if data != "" {
|
||||
err := json.Unmarshal([]byte(data), &group)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
func (s *GroupStore) Set(ctx context.Context, group *storage.Group) error {
|
||||
cacheKey := s.generateCacheKey(group.ID)
|
||||
|
||||
json, err := json.Marshal(group)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.rdb.Set(ctx, cacheKey, json, RolesExpTime).Err()
|
||||
}
|
||||
|
||||
func (s *GroupStore) Delete(ctx context.Context, id int64) {
|
||||
cacheKey := s.generateCacheKey(id)
|
||||
s.rdb.Del(ctx, cacheKey)
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user