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)
|
||||
}
|
6
server/app/permissions.go
Normal file
6
server/app/permissions.go
Normal file
|
@ -0,0 +1,6 @@
|
|||
package app
|
||||
|
||||
// ToDo: implement
|
||||
func (a *App) HasPermissionToGame(userID, gameID int) bool {
|
||||
return true
|
||||
}
|
15
server/app/post.go
Normal file
15
server/app/post.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.ctrlz.es/mgdelacroix/craban/model"
|
||||
)
|
||||
|
||||
func (a *App) CreatePost(post *model.Post) (*model.Post, error) {
|
||||
if err := post.IsValid(); err != nil {
|
||||
return nil, fmt.Errorf("invalid post for creation: %w", err)
|
||||
}
|
||||
|
||||
return a.Store.Post().Create(post)
|
||||
}
|
|
@ -1,5 +1,9 @@
|
|||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Post struct {
|
||||
ID int `json:"id"`
|
||||
UserID int `json:"user_id"`
|
||||
|
@ -7,3 +11,23 @@ type Post struct {
|
|||
CreatedAt int `json:"createdat"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
func (p *Post) IsValid() error {
|
||||
if p.UserID == 0 {
|
||||
return fmt.Errorf("user id must not be empty")
|
||||
}
|
||||
|
||||
if p.GameID == 0 {
|
||||
return fmt.Errorf("game id must not be empty")
|
||||
}
|
||||
|
||||
if p.CreatedAt == 0 {
|
||||
return fmt.Errorf("created at must not be empty")
|
||||
}
|
||||
|
||||
if p.Body == "" {
|
||||
return fmt.Errorf("body must not be empty")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -2,9 +2,14 @@ package store
|
|||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
sq "github.com/Masterminds/squirrel"
|
||||
|
||||
"git.ctrlz.es/mgdelacroix/craban/model"
|
||||
)
|
||||
|
||||
var postColums = []string{"id", "user_id", "game_id", "createdat", "body"}
|
||||
var postColumns = []string{"id", "user_id", "game_id", "createdat", "body"}
|
||||
|
||||
type PostStore struct {
|
||||
Conn *sql.DB
|
||||
|
@ -13,3 +18,84 @@ type PostStore struct {
|
|||
func NewPostStore(s *Store) *PostStore {
|
||||
return &PostStore{Conn: s.Conn}
|
||||
}
|
||||
|
||||
func (ps *PostStore) Q() sq.StatementBuilderType {
|
||||
return sq.StatementBuilder.RunWith(ps.Conn)
|
||||
}
|
||||
|
||||
func (ps *PostStore) postsFromRows(rows *sql.Rows) ([]*model.Post, error) {
|
||||
posts := []*model.Post{}
|
||||
|
||||
for rows.Next() {
|
||||
var post model.Post
|
||||
|
||||
err := rows.Scan(
|
||||
&post.ID,
|
||||
&post.UserID,
|
||||
&post.GameID,
|
||||
&post.CreatedAt,
|
||||
&post.Body,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posts = append(posts, &post)
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
func (ps *PostStore) GetByID(id int) (*model.Post, error) {
|
||||
return ps.getPostByCondition(sq.Eq{"id": id})
|
||||
}
|
||||
|
||||
func (ps *PostStore) getPostByCondition(condition sq.Eq) (*model.Post, error) {
|
||||
posts, err := ps.getPostsByCondition(condition)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return posts[0], nil
|
||||
}
|
||||
|
||||
func (ps *PostStore) getPostsByCondition(condition sq.Eq) ([]*model.Post, error) {
|
||||
rows, err := ps.Q().Select(postColumns...).
|
||||
From("posts").
|
||||
Where(condition).
|
||||
Query()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot get posts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
posts, err := ps.postsFromRows(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot get posts from rows: %w", err)
|
||||
}
|
||||
|
||||
if len(posts) == 0 {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
func (ps *PostStore) Create(post *model.Post) (*model.Post, error) {
|
||||
query := ps.Q().Insert("posts").
|
||||
Columns(postColumns[1:]...).
|
||||
Values(post.UserID, post.GameID, post.CreatedAt, post.Body)
|
||||
|
||||
res, err := query.Exec()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot insert post: %w", err)
|
||||
}
|
||||
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot get last insert id for created post: %w", err)
|
||||
}
|
||||
|
||||
return ps.GetByID(int(id))
|
||||
|
||||
}
|
||||
|
|
|
@ -58,6 +58,10 @@ func (s *Store) Game() *GameStore {
|
|||
return s.gameStore
|
||||
}
|
||||
|
||||
func (s *Store) Post() *PostStore {
|
||||
return s.postStore
|
||||
}
|
||||
|
||||
func (s *Store) EnsureSchema() error {
|
||||
schema := `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
|
|
|
@ -42,6 +42,7 @@ func (w *WebServer) RegisterRoutes(api *api.API) {
|
|||
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")
|
||||
apiRouter.HandleFunc("/games/{id:[0-9]+}/post", api.Secured(api.CreatePostForGame)).Methods("POST")
|
||||
|
||||
staticFSSub, _ := fs.Sub(staticFS, "static")
|
||||
staticFSHandler := StaticFSHandler{http.FileServer(http.FS(staticFSSub))}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue