From 253e462536cf91690b4ace57f5fba5f687b81ebc Mon Sep 17 00:00:00 2001 From: Flashfyre Date: Mon, 1 Apr 2024 21:42:48 -0400 Subject: [PATCH] Cache player count instead of querying per user --- api/game.go | 25 ++++++++++++++++++++----- pokerogue-server.go | 1 + 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/api/game.go b/api/game.go index c958e6c..5efedf4 100644 --- a/api/game.go +++ b/api/game.go @@ -3,20 +3,35 @@ package api import ( "encoding/json" "fmt" + "log" "net/http" + "time" "github.com/Flashfyre/pokerogue-server/db" + "github.com/go-co-op/gocron" ) -// /game/playercount - get player count +var ( + playerCountScheduler = gocron.NewScheduler(time.UTC) + playerCount = 0 +) -func (s *Server) HandlePlayerCountGet(w http.ResponseWriter, r *http.Request) { - playerCount, err := db.FetchPlayerCount() +func SchedulePlayerCountRefresh() { + playerCountScheduler.Every(10).Second().Do(UpdatePlayerCount) + playerCountScheduler.StartAsync() +} + +func UpdatePlayerCount() { + var err error + playerCount, err = db.FetchPlayerCount() if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return + log.Print(err.Error()) } +} +// /game/playercount - get player count + +func (s *Server) HandlePlayerCountGet(w http.ResponseWriter, r *http.Request) { response, err := json.Marshal(playerCount) if err != nil { http.Error(w, fmt.Sprintf("failed to marshal response json: %s", err), http.StatusInternalServerError) diff --git a/pokerogue-server.go b/pokerogue-server.go index 73e2a24..f755e9b 100644 --- a/pokerogue-server.go +++ b/pokerogue-server.go @@ -43,6 +43,7 @@ func main() { os.Chmod(*addr, 0777) } + api.SchedulePlayerCountRefresh() api.ScheduleDailyRunRefresh() api.InitDailyRun()