2021-09-13 21:45:08 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2021-09-15 23:37:07 +01:00
|
|
|
"strconv"
|
2021-09-13 21:45:08 +01:00
|
|
|
|
2021-09-15 23:37:07 +01:00
|
|
|
"github.com/gorilla/mux"
|
2021-09-13 21:45:08 +01:00
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (a *API) CreateGame(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user, _ := UserFromRequest(r)
|
|
|
|
if !user.Admin {
|
|
|
|
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
body := ParseBody(r)
|
|
|
|
name := body.String("name")
|
|
|
|
|
|
|
|
if name == "" {
|
|
|
|
http.Error(w, fmt.Sprintf("%s: name should not be empty", http.StatusText(http.StatusBadRequest)), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
game, err := a.App.CreateGame(name, user.ID)
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("game couldn't be created")
|
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
JSON(w, game, 201)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *API) ListGames(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user, _ := UserFromRequest(r)
|
|
|
|
|
|
|
|
games, err := a.App.ListGamesForUser(user.ID)
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("games couldn't be fetch")
|
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
JSON(w, games, 200)
|
|
|
|
}
|
2021-09-15 23:37:07 +01:00
|
|
|
|
|
|
|
func (a *API) GetGame(w http.ResponseWriter, r *http.Request) {
|
|
|
|
gameID, _ := strconv.Atoi(mux.Vars(r)["id"])
|
|
|
|
user, _ := UserFromRequest(r)
|
|
|
|
|
|
|
|
game, err := a.App.GetGameForUser(gameID, user.ID)
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("game couldn't be fetch")
|
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if game == nil {
|
|
|
|
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
JSON(w, game, 200)
|
|
|
|
}
|