Bugfixes. Optimizations/refactor. Add redis for player-cache. Add docker files. Replace sqlite dep. Single-Calc for existing players. Game-Metrics in JSON.
This commit is contained in:
55
internal/cache/cache.go
vendored
Normal file
55
internal/cache/cache.go
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"InfantrySkillCalculator/models"
|
||||
"InfantrySkillCalculator/utils"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var ctx = context.Background()
|
||||
|
||||
func GetValue(key string) (string, error) {
|
||||
val, err := models.Cache.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return "", err // cache miss or error
|
||||
} else {
|
||||
return val, nil // cache hit
|
||||
}
|
||||
}
|
||||
|
||||
func SetValue(key string, value interface{}) error {
|
||||
return models.Cache.Set(ctx, key, value, utils.PlayerCacheLifetime).Err()
|
||||
}
|
||||
|
||||
func SetScore(playerId uint, gameTag string, score float32) error {
|
||||
key := GetPlayerCacheKey(playerId, gameTag)
|
||||
return SetValue(key, score)
|
||||
}
|
||||
|
||||
func GetScore(playerId uint, gameTag string) (float32, error) {
|
||||
key := GetPlayerCacheKey(playerId, gameTag)
|
||||
val, err := GetValue(key)
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return -1.0, nil // cache miss
|
||||
} else if err != nil {
|
||||
return -1.0, err // cache error
|
||||
} else {
|
||||
return utils.StringToFloat(val), nil // cache hit
|
||||
}
|
||||
}
|
||||
|
||||
func DeleteScore(playerId uint, gameTag string) error {
|
||||
key := GetPlayerCacheKey(playerId, gameTag)
|
||||
return models.Cache.Del(ctx, key).Err()
|
||||
}
|
||||
|
||||
func PurgeCache() error {
|
||||
return models.Cache.FlushAll(ctx).Err()
|
||||
}
|
||||
|
||||
func GetPlayerCacheKey(playerId uint, gameTag string) string {
|
||||
return fmt.Sprintf("player:%d:game:%s", playerId, gameTag)
|
||||
}
|
||||
Reference in New Issue
Block a user