From 29412f92fc0b7b543cbba8a00f1f599333a3ab3b Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Thu, 26 Jan 2023 10:17:12 +0200 Subject: [PATCH] feat(sdbapi): endpoint for getting own games --- sdbapi/apierror/apierror.go | 1 + sdbapi/db/game.go | 28 +++++++++++++++++++++++++++ sdbapi/handlers/mygames.go | 38 +++++++++++++++++++++++++++++++++++++ sdbapi/main.go | 2 +- 4 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 sdbapi/db/game.go create mode 100644 sdbapi/handlers/mygames.go diff --git a/sdbapi/apierror/apierror.go b/sdbapi/apierror/apierror.go index b28d8ee..855c53e 100644 --- a/sdbapi/apierror/apierror.go +++ b/sdbapi/apierror/apierror.go @@ -24,4 +24,5 @@ const ( GameCreationFailed string = "game creation failed" GetAllFormingFailed string = "something went wrong while fetching all forming games" GameStatePatchFailed string = "failed to patch game state" + NoGamesForUser = "no games found for user" ) diff --git a/sdbapi/db/game.go b/sdbapi/db/game.go new file mode 100644 index 0000000..2246c84 --- /dev/null +++ b/sdbapi/db/game.go @@ -0,0 +1,28 @@ +/* + * This file is part of sdbapi + * Copyright (C) 2022 Jonni Liljamo + * + * Licensed under GPL-3.0-only. + * See LICENSE for licensing information. + */ + +package db + +import ( + "api/apierror" + "api/models" + + "errors" +) + +// get games for a specific user with email +func GetGamesForUser(id string) ([]models.Game, error) { + var games []models.Game + game_records := DbConn.Where("p1 = ? OR p2 = ?", id, id).Find(&games) + if game_records.Error != nil { + return []models.Game{}, errors.New(apierror.NoGamesForUser) + } + + return games, nil +} + diff --git a/sdbapi/handlers/mygames.go b/sdbapi/handlers/mygames.go new file mode 100644 index 0000000..cd67010 --- /dev/null +++ b/sdbapi/handlers/mygames.go @@ -0,0 +1,38 @@ +/* + * This file is part of sdbapi + * Copyright (C) 2022 Jonni Liljamo + * + * Licensed under GPL-3.0-only. + * See LICENSE for licensing information. + */ + +package handlers + +import ( + "api/apierror" + "api/db" + "api/models" + "net/http" + + "github.com/gin-gonic/gin" +) + +func MyGames(c *gin.Context) { + var user models.User + record := db.DbConn.Where("email = ?", c.GetString("email")).First(&user) + if record.Error != nil { + c.JSON(http.StatusNotFound, gin.H{"error": apierror.UserNotFound}) + c.Abort() + return + } + + games, err := db.GetGamesForUser(user.ID) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.Abort() + return + } + + c.JSON(http.StatusOK, gin.H{"games": games}) +} + diff --git a/sdbapi/main.go b/sdbapi/main.go index 263f6b0..c243802 100644 --- a/sdbapi/main.go +++ b/sdbapi/main.go @@ -51,7 +51,7 @@ func createRouter() *gin.Engine { game.GET("/all_forming", handlers.FormingGames) game.POST("/create", handlers.CreateGame) game.PATCH("/:id/state", handlers.PatchGameState) - //game.GET("/for_user/:id", handlers.UsersGames) + game.GET("/my_games", handlers.MyGames) } } return router -- 2.44.1