feat: initial commit
This commit is contained in:
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/FernandoVideira/LK_API_Temp/internal/store"
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
type UserStore struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
const UserExpTime = time.Hour * 24
|
||||
|
||||
func (s *UserStore) Get(ctx context.Context, id int64) (*store.User, error) {
|
||||
cacheKey := fmt.Sprintf("user-%d", id)
|
||||
|
||||
data, err := s.rdb.Get(ctx, cacheKey).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var user store.User
|
||||
if data != "" {
|
||||
err := json.Unmarshal([]byte(data), &user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *UserStore) Set(ctx context.Context, user *store.User) error {
|
||||
|
||||
if user.ID == 0 {
|
||||
return fmt.Errorf("user ID is required")
|
||||
}
|
||||
|
||||
cacheKey := fmt.Sprintf("user-%d", user.ID)
|
||||
|
||||
json, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.rdb.SetEX(ctx, cacheKey, json, UserExpTime).Err()
|
||||
}
|
||||
|
||||
func (s *UserStore) Delete(ctx context.Context, id int64) error {
|
||||
cacheKey := fmt.Sprintf("user-%d", id)
|
||||
|
||||
return s.rdb.Del(ctx, cacheKey).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user