48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.ctrlz.es/mgdelacroix/craban/model"
|
|
"git.ctrlz.es/mgdelacroix/craban/utils"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (a *API) CreatePostForGame(w http.ResponseWriter, r *http.Request) {
|
|
gameID, _ := strconv.Atoi(mux.Vars(r)["id"])
|
|
user, _ := UserFromRequest(r)
|
|
|
|
body := ParseBody(r)
|
|
message := body.String("message")
|
|
|
|
if message == "" {
|
|
http.Error(w, fmt.Sprintf("%s: message should not be empty", http.StatusText(http.StatusBadRequest)), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if !a.App.HasPermissionToGame(user.ID, gameID) {
|
|
http.Error(w, fmt.Sprintf("%s: user cannot post in this game", http.StatusText(http.StatusForbidden)), http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
post := &model.Post{
|
|
UserID: user.ID,
|
|
GameID: gameID,
|
|
CreatedAt: utils.Millis(time.Now()),
|
|
Body: message,
|
|
}
|
|
|
|
newPost, err := a.App.CreatePost(post)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("post couldn't be saved")
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
JSON(w, newPost, 201)
|
|
}
|