56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
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)
|
|
}
|