add create handler

This commit is contained in:
Jeffrey Duroyon
2020-05-17 01:30:15 +02:00
parent 38950ebafd
commit 65bba00863
3 changed files with 123 additions and 9 deletions

View File

@@ -1,6 +1,7 @@
package handlers
import (
"encoding/json"
"github.com/gin-gonic/gin"
"hamster-tycoon/storage/dao"
"hamster-tycoon/storage/model"
@@ -10,25 +11,25 @@ import (
)
func (hc *handlersContext) getAllHamsters(c *gin.Context) {
users, err := hc.db.GetAllHamsters()
hamsters, err := hc.db.GetAllHamsters()
if err != nil {
utils.GetLoggerFromCtx(c).WithError(err).Error("error while getting hamsters")
utils.JSONErrorWithMessage(c.Writer, model.ErrInternalServer, "Error while getting hamsters")
return
}
utils.JSON(c.Writer, http.StatusOK, users)
utils.JSON(c.Writer, http.StatusOK, hamsters)
}
func (hc *handlersContext) getAHamster(c *gin.Context) {
userID := c.Param("hamsterId")
hamsterID := c.Param("hamsterId")
err := hc.validator.VarCtx(c, userID, "uuid4")
err := hc.validator.VarCtx(c, hamsterID, "uuid4")
if err != nil {
utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
return
}
user, err := hc.db.GetHamsterById(userID)
hamster, err := hc.db.GetHamsterById(hamsterID)
if e, ok := err.(*dao.DAOError); ok {
switch {
case e.Type == dao.ErrTypeNotFound:
@@ -45,16 +46,53 @@ func (hc *handlersContext) getAHamster(c *gin.Context) {
return
}
if user == nil {
if hamster == nil {
utils.JSONErrorWithMessage(c.Writer, model.ErrNotFound, "Hamster not found")
return
}
utils.JSON(c.Writer, http.StatusOK, user)
utils.JSON(c.Writer, http.StatusOK, hamster)
}
func (hc *handlersContext) createAHamster(c *gin.Context) {
b, err := c.GetRawData()
if err != nil {
utils.GetLoggerFromCtx(c).WithError(err).Error("error while creating hamster, read data fail")
utils.JSONError(c.Writer, model.ErrInternalServer)
return
}
hamsterToCreate := model.Hamster{}
err = json.Unmarshal(b, &hamsterToCreate)
if err != nil {
utils.JSONError(c.Writer, model.ErrBadRequestFormat)
return
}
err = hc.validator.StructCtx(c, hamsterToCreate)
if err != nil {
utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
return
}
err = hc.db.CreateHamster(&hamsterToCreate)
if e, ok := err.(*dao.DAOError); ok {
switch {
case e.Type == dao.ErrTypeDuplicate:
utils.JSONErrorWithMessage(c.Writer, model.ErrAlreadyExists, "Hamster already exists")
return
default:
utils.GetLoggerFromCtx(c).WithError(err).WithField("type", e.Type).Error("error CreateHamster: Error type not handled")
utils.JSONError(c.Writer, model.ErrInternalServer)
return
}
} else if err != nil {
utils.GetLoggerFromCtx(c).WithError(err).Error("error while creating hamster")
utils.JSONError(c.Writer, model.ErrInternalServer)
return
}
utils.JSON(c.Writer, http.StatusCreated, hamsterToCreate)
}
func (hc *handlersContext) updateAHamster(c *gin.Context) {