add update and delete endpoints to game controller and router

This commit is contained in:
Chris Cromer 2023-02-01 14:43:36 -03:00 committed by Martin Araneda
parent 6ea3e89741
commit 41d5fc2d4b
2 changed files with 61 additions and 3 deletions

View File

@ -5,6 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"net/http" "net/http"
"strconv"
"git.cromer.cl/Proyecto-Titulo/alai-server/backend/database" "git.cromer.cl/Proyecto-Titulo/alai-server/backend/database"
"git.cromer.cl/Proyecto-Titulo/alai-server/backend/models" "git.cromer.cl/Proyecto-Titulo/alai-server/backend/models"
@ -90,3 +91,59 @@ func CreateGame(writer http.ResponseWriter, request *http.Request, params httpro
return return
} }
} }
func UpdateGame(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
gdb := database.Connect()
defer database.Close(gdb)
var game models.Game
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&game)
if err != nil {
utils.JSONErrorOutput(writer, http.StatusBadRequest, err.Error())
return
}
game.ID, err = strconv.ParseUint(params.ByName("id"), 10, 64)
if err != nil {
utils.JSONErrorOutput(writer, http.StatusBadRequest, err.Error())
return
}
result := gdb.Updates(&game)
if result.Error != nil {
utils.JSONErrorOutput(writer, http.StatusBadRequest, result.Error.Error())
return
} else if result.RowsAffected == 0 {
writer.WriteHeader(http.StatusNotFound)
return
} else {
writer.WriteHeader(http.StatusNoContent)
}
}
func DeleteGame(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
gdb := database.Connect()
defer database.Close(gdb)
var game models.Game
var err error
game.ID, err = strconv.ParseUint(params.ByName("id"), 10, 64)
if err != nil {
utils.JSONErrorOutput(writer, http.StatusBadRequest, err.Error())
return
}
result := gdb.Delete(&game)
if result.Error != nil {
utils.JSONErrorOutput(writer, http.StatusBadRequest, result.Error.Error())
return
} else if result.RowsAffected == 0 {
writer.WriteHeader(http.StatusNotFound)
return
} else {
writer.WriteHeader(http.StatusNoContent)
}
}

View File

@ -2,13 +2,14 @@ package routes
import ( import (
"git.cromer.cl/Proyecto-Titulo/alai-server/backend/controllers" "git.cromer.cl/Proyecto-Titulo/alai-server/backend/controllers"
"git.cromer.cl/Proyecto-Titulo/alai-server/backend/middlewares"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
) )
func GameRoutes(router *httprouter.Router) { func GameRoutes(router *httprouter.Router) {
router.GET("/game", middlewares.Authenticate(controllers.ListGame)) router.GET("/game", controllers.ListGame)
router.GET("/game/:id", middlewares.Authenticate(controllers.GetGame)) router.GET("/game/:id", controllers.GetGame)
router.POST("/game", controllers.CreateGame) router.POST("/game", controllers.CreateGame)
router.PATCH("/game/:id", controllers.UpdateGame)
router.DELETE("/game/:id", controllers.DeleteGame)
} }