Add getGame and listGames endpoints, client methods and initial components
This commit is contained in:
parent
ff455414f8
commit
08ab312f92
8 changed files with 136 additions and 8 deletions
|
@ -3,7 +3,9 @@ package api
|
|||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
@ -44,3 +46,22 @@ func (a *API) ListGames(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
JSON(w, games, 200)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
|
|
@ -14,6 +14,20 @@ func (a *App) AddMember(gameID, userID int, role string) (*model.GameMember, err
|
|||
return a.Store.Game().AddMember(gameID, userID, role)
|
||||
}
|
||||
|
||||
func (a *App) GetGameForUser(gameID, userID int) (*model.Game, error) {
|
||||
game, err := a.Store.Game().GetByID(gameID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// ToDo: create a helper like userIsMember or
|
||||
// userHasPermissionToGame instead of checking ownership
|
||||
if game.UserID != userID {
|
||||
return nil, nil
|
||||
}
|
||||
return game, nil
|
||||
}
|
||||
|
||||
func (a *App) ListGames() ([]*model.Game, error) {
|
||||
games, err := a.Store.Game().List()
|
||||
if err == sql.ErrNoRows {
|
||||
|
|
|
@ -41,6 +41,7 @@ func (w *WebServer) RegisterRoutes(api *api.API) {
|
|||
apiRouter.HandleFunc("/users", api.Secured(api.CreateUser)).Methods("POST")
|
||||
apiRouter.HandleFunc("/games", api.Secured(api.CreateGame)).Methods("POST")
|
||||
apiRouter.HandleFunc("/games", api.Secured(api.ListGames)).Methods("GET")
|
||||
apiRouter.HandleFunc("/games/{id:[0-9]+}", api.Secured(api.GetGame)).Methods("GET")
|
||||
|
||||
staticFSSub, _ := fs.Sub(staticFS, "static")
|
||||
staticFSHandler := StaticFSHandler{http.FileServer(http.FS(staticFSSub))}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue