Add create post endpoint and check target to the makefile
This commit is contained in:
parent
08ab312f92
commit
3067beb96c
12 changed files with 280 additions and 5 deletions
48
server/api/post.go
Normal file
48
server/api/post.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue