feat: initial commit

This commit is contained in:
2025-03-31 16:17:35 +01:00
commit 6719f8a61a
91 changed files with 7119 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
package cache
import (
"context"
"github.com/FernandoVideira/LK_API_Temp/internal/store"
"github.com/stretchr/testify/mock"
)
func NewMockCache() Storage {
return Storage{
Users: &MockUserStore{},
}
}
type MockUserStore struct {
mock.Mock
}
func (m *MockUserStore) Get(ctx context.Context, id int64) (*store.User, error) {
args := m.Called(id)
return nil, args.Error(1)
}
func (m *MockUserStore) Set(ctx context.Context, user *store.User) error {
args := m.Called(user)
return args.Error(0)
}
func (m *MockUserStore) Delete(ctx context.Context, id int64) error {
args := m.Called(id)
return args.Error(0)
}
+11
View File
@@ -0,0 +1,11 @@
package cache
import "github.com/go-redis/redis/v8"
func NewRedisClient(addr, pw string, db int) *redis.Client {
return redis.NewClient(&redis.Options{
Addr: addr,
Password: pw,
DB: db,
})
}
+22
View File
@@ -0,0 +1,22 @@
package cache
import (
"context"
"github.com/FernandoVideira/LK_API_Temp/internal/store"
"github.com/go-redis/redis/v8"
)
type Storage struct {
Users interface {
Get(context.Context, int64) (*store.User, error)
Set(context.Context, *store.User) error
Delete(context.Context, int64) error
}
}
func NewRedisStorage(rdb *redis.Client) Storage {
return Storage{
Users: &UserStore{rdb: rdb},
}
}
+60
View File
@@ -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()
}