add create handler
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"hamster-tycoon/storage/dao"
|
||||
"hamster-tycoon/storage/model"
|
||||
@@ -10,13 +11,13 @@ import (
|
||||
)
|
||||
|
||||
func (hc *handlersContext) getAllGames(c *gin.Context) {
|
||||
users, err := hc.db.GetAllGames()
|
||||
games, err := hc.db.GetAllGames()
|
||||
if err != nil {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).Error("error while getting games")
|
||||
utils.JSONErrorWithMessage(c.Writer, model.ErrInternalServer, "Error while getting games")
|
||||
return
|
||||
}
|
||||
utils.JSON(c.Writer, http.StatusOK, users)
|
||||
utils.JSON(c.Writer, http.StatusOK, games)
|
||||
}
|
||||
|
||||
func (hc *handlersContext) getAGame(c *gin.Context) {
|
||||
@@ -54,7 +55,44 @@ func (hc *handlersContext) getAGame(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (hc *handlersContext) createAGame(c *gin.Context) {
|
||||
b, err := c.GetRawData()
|
||||
if err != nil {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).Error("error while creating game, read data fail")
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
gameToCreate := model.Game{}
|
||||
err = json.Unmarshal(b, &gameToCreate)
|
||||
if err != nil {
|
||||
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
|
||||
return
|
||||
}
|
||||
|
||||
err = hc.validator.StructCtx(c, gameToCreate)
|
||||
if err != nil {
|
||||
utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
|
||||
return
|
||||
}
|
||||
|
||||
err = hc.db.CreateGame(&gameToCreate)
|
||||
if e, ok := err.(*dao.DAOError); ok {
|
||||
switch {
|
||||
case e.Type == dao.ErrTypeDuplicate:
|
||||
utils.JSONErrorWithMessage(c.Writer, model.ErrAlreadyExists, "Game already exists")
|
||||
return
|
||||
default:
|
||||
utils.GetLoggerFromCtx(c).WithError(err).WithField("type", e.Type).Error("error CreateGame: Error type not handled")
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
} else if err != nil {
|
||||
utils.GetLoggerFromCtx(c).WithError(err).Error("error while creating game")
|
||||
utils.JSONError(c.Writer, model.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
utils.JSON(c.Writer, http.StatusCreated, gameToCreate)
|
||||
}
|
||||
|
||||
func (hc *handlersContext) updateAGame(c *gin.Context) {
|
||||
|
||||
Reference in New Issue
Block a user