Handlers, DB, Cache
This commit is contained in:
39
internal/service/cache/cache_service.go
vendored
Normal file
39
internal/service/cache/cache_service.go
vendored
Normal 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()
|
||||
}
|
||||
7
internal/service/cache/config/cache.go
vendored
Normal file
7
internal/service/cache/config/cache.go
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
type Cache struct {
|
||||
TTL time.Duration
|
||||
}
|
||||
50
internal/service/cache/module.go
vendored
Normal file
50
internal/service/cache/module.go
vendored
Normal 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
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user