84 lines
1.9 KiB
Go
84 lines
1.9 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 GetScores(players []models.Player, gameTag string) ([]float32, error) {
|
|
vals, err := models.Cache.Pipelined(ctx, func(pipe redis.Pipeliner) error {
|
|
for _, p := range players {
|
|
key := GetPlayerCacheKey(p.ID, gameTag)
|
|
pipe.Get(ctx, key)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
return nil, err
|
|
}
|
|
|
|
var scores []float32
|
|
for _, val := range vals {
|
|
score, err := val.(*redis.StringCmd).Float32()
|
|
|
|
if errors.Is(err, redis.Nil) { // cache miss
|
|
score = -1
|
|
err = nil
|
|
} else if err != nil { // cache error
|
|
score = -1
|
|
}
|
|
|
|
scores = append(scores, score)
|
|
}
|
|
return scores, nil
|
|
}
|
|
|
|
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)
|
|
}
|