craban/server/services/store/post.go
2021-09-25 17:23:56 +02:00

101 lines
2 KiB
Go

package store
import (
"database/sql"
"fmt"
sq "github.com/Masterminds/squirrel"
"git.ctrlz.es/mgdelacroix/craban/model"
)
var postColumns = []string{"id", "user_id", "game_id", "createdat", "body"}
type PostStore struct {
Conn *sql.DB
}
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))
}