Add run configs. Add redis for cache. Add cache-get in player-list.

This commit is contained in:
MaxJa4
2024-01-20 17:47:39 +01:00
parent 9e3e2723d3
commit 069d76520e
10 changed files with 124 additions and 9 deletions

View File

@@ -3,7 +3,11 @@ package controllers
import (
"InfantrySkillCalculator/models"
"InfantrySkillCalculator/utils"
"context"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"net/http"
@@ -22,16 +26,32 @@ type UpdateCacheInput struct {
Score float32 `json:"score" gorm:"default:-1.0"`
}
// GetCacheByPlayerID GET /cache/:id?game=TAG
var ctx = context.Background()
// GetCacheByPlayerID GET /cache/:player_id?game_id=TAG
func GetCacheByPlayerID(c *gin.Context) {
var cache models.PlayerCache
playerId := utils.StringToUint(c.Param("player_id"))
gameId := utils.StringToUint(c.Request.URL.Query().Get("game_id"))
if err := FindCacheGin(&cache, c).Error; err != nil {
val, err := GetCacheByPlayerIDGorm(playerId, gameId)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
} else {
c.JSON(http.StatusOK, val)
}
}
c.JSON(http.StatusOK, cache)
func GetCacheByPlayerIDGorm(playerId uint, gameId uint) (float32, error) {
key := fmt.Sprintf("player:%d:game:%d", playerId, gameId)
val, err := models.Cache.Get(ctx, key).Result()
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
}
}
// AddCache POST /cache