From 49d9fa996e825a3349955c41d13307f33d0e7421 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Mon, 29 Jul 2024 22:27:20 +0900 Subject: refactor(backend) --- backend/game/http.go | 30 ++++++++---------------------- backend/game/hub.go | 4 ++++ 2 files changed, 12 insertions(+), 22 deletions(-) (limited to 'backend') diff --git a/backend/game/http.go b/backend/game/http.go index 8cf7322..d955fa3 100644 --- a/backend/game/http.go +++ b/backend/game/http.go @@ -27,22 +27,15 @@ func (h *sockHandler) HandleSockGolfPlay(c echo.Context) error { } // TODO: check user permission - gameId := c.Param("gameId") - gameIdInt, err := strconv.Atoi(gameId) + gameID, err := strconv.Atoi(c.Param("gameId")) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid game id") } - var foundHub *gameHub - for _, hub := range h.hubs.hubs { - if hub.game.gameID == gameIdInt { - foundHub = hub - break - } - } - if foundHub == nil { + hub := h.hubs.getHub(gameID) + if hub == nil { return echo.NewHTTPError(http.StatusNotFound, "Game not found") } - return servePlayerWs(foundHub, c.Response(), c.Request(), claims.UserID) + return servePlayerWs(hub, c.Response(), c.Request(), claims.UserID) } func (h *sockHandler) HandleSockGolfWatch(c echo.Context) error { @@ -55,20 +48,13 @@ func (h *sockHandler) HandleSockGolfWatch(c echo.Context) error { return echo.NewHTTPError(http.StatusForbidden, "Permission denied") } - gameId := c.Param("gameId") - gameIdInt, err := strconv.Atoi(gameId) + gameID, err := strconv.Atoi(c.Param("gameId")) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid game id") } - var foundHub *gameHub - for _, hub := range h.hubs.hubs { - if hub.game.gameID == gameIdInt { - foundHub = hub - break - } - } - if foundHub == nil { + hub := h.hubs.getHub(gameID) + if hub == nil { return echo.NewHTTPError(http.StatusNotFound, "Game not found") } - return serveWatcherWs(foundHub, c.Response(), c.Request()) + return serveWatcherWs(hub, c.Response(), c.Request()) } diff --git a/backend/game/hub.go b/backend/game/hub.go index 770d257..54ea2d0 100644 --- a/backend/game/hub.go +++ b/backend/game/hub.go @@ -255,6 +255,10 @@ func (hubs *GameHubs) Close() { } } +func (hubs *GameHubs) getHub(gameID int) *gameHub { + return hubs.hubs[gameID] +} + func (hubs *GameHubs) RestoreFromDB(ctx context.Context) error { games, err := hubs.q.ListGames(ctx) if err != nil { -- cgit v1.2.3-70-g09d2