Handlers, DB, Cache

This commit is contained in:
2026-03-10 19:17:43 +03:00
parent e56b1f1305
commit 968c030939
23 changed files with 566 additions and 34 deletions

39
internal/service/cache/cache_service.go vendored Normal file
View File

@@ -0,0 +1,39 @@
package cache
import (
"time"
"github.com/jellydator/ttlcache/v3"
"payouts/internal/service/database/orm"
)
type cacheService struct {
cache *ttlcache.Cache[string, orm.User]
}
func NewSessionCache(ttl time.Duration) (Service, error) {
return &cacheService{
cache: ttlcache.New(ttlcache.WithTTL[string, orm.User](ttl)),
}, nil
}
// PutSession implements [Service].
func (c *cacheService) PutSession(sessionID string, user orm.User) {
c.cache.Set(sessionID, user, ttlcache.DefaultTTL)
}
// GetUserFromSession implements [Service].
func (c *cacheService) GetSession(sessionId string) (orm.User, error) {
if !c.cache.Has(sessionId) {
return orm.User{}, NoSessionFound
}
cachedItem := c.cache.Get(sessionId)
return cachedItem.Value(), nil
}
// StartBackground implements [Service].
func (c *cacheService) StartBackground() {
c.cache.Start()
}

View File

@@ -0,0 +1,7 @@
package config
import "time"
type Cache struct {
TTL time.Duration
}

50
internal/service/cache/module.go vendored Normal file
View File

@@ -0,0 +1,50 @@
package cache
import (
"context"
"errors"
"go.uber.org/fx"
"payouts/internal/config"
"payouts/internal/service/database/orm"
)
var Module = fx.Options(
fx.Provide(New),
fx.Invoke(StartCache),
)
var NoSessionFound = errors.New("no session found")
type Service interface {
PutSession(string, orm.User)
GetSession(string) (orm.User, error)
StartBackground()
}
type Params struct {
fx.In
AppConfig *config.App
}
func New(p Params) (Service, error) {
return NewSessionCache(p.AppConfig.Cache.TTL)
}
// RegisterRoutes registers the api routes and starts the http server
func StartCache(s Service, lc fx.Lifecycle) {
lc.Append(fx.Hook{
OnStart: func(c context.Context) error {
go func() {
s.StartBackground()
}()
return nil
},
OnStop: func(ctx context.Context) error {
return nil
},
})
}