-
Notifications
You must be signed in to change notification settings - Fork 0
/
article.go
74 lines (59 loc) · 2.24 KB
/
article.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package models
import (
"errors"
"github.com/rank-a-thon/rank-a-thon/backend/db"
"github.com/rank-a-thon/rank-a-thon/backend/forms"
)
// Article ...
type Article struct {
ID int64 `db:"id, primarykey, autoincrement" json:"id"`
UserID int64 `db:"user_id" json:"-"`
Title string `db:"title" json:"title"`
Content string `db:"content" json:"content"`
UpdatedAt int64 `db:"updated_at" json:"updated_at"`
CreatedAt int64 `db:"created_at" json:"created_at"`
User *JSONRaw `db:"user" json:"user"`
}
// ArticleModel ...
type ArticleModel struct{}
// Create ...
func (m ArticleModel) Create(userID int64, form forms.ArticleForm) (articleID int64, err error) {
err = db.GetDB().QueryRow(
"INSERT INTO public.article(user_id, title, content) VALUES($1, $2, $3) RETURNING id",
userID, form.Title, form.Content).Scan(&articleID)
return articleID, err
}
// One ...
func (m ArticleModel) One(userID, id int64) (article Article, err error) {
err = db.GetDB().SelectOne(
&article,
"SELECT a.id, a.title, a.content, a.updated_at, a.created_at, json_build_object('id', u.id, 'name', u.name, 'email', u.email) AS user FROM public.article a LEFT JOIN public.user u ON a.user_id = u.id WHERE a.user_id=$1 AND a.id=$2 LIMIT 1",
userID, id)
return article, err
}
// All ...
func (m ArticleModel) All(userID int64) (articles []Article, err error) {
_, err = db.GetDB().Select(
&articles,
"SELECT a.id, a.title, a.content, a.updated_at, a.created_at, json_build_object('id', u.id, 'name', u.name, 'email', u.email) AS user FROM public.article a LEFT JOIN public.user u ON a.user_id = u.id WHERE a.user_id=$1 ORDER BY a.id DESC",
userID)
return articles, err
}
// Update ...
func (m ArticleModel) Update(userID int64, id int64, form forms.ArticleForm) (err error) {
_, err = m.One(userID, id)
if err != nil {
return errors.New("Article not found")
}
_, err = db.GetDB().Exec("UPDATE public.article SET title=$2, content=$3 WHERE id=$1", id, form.Title, form.Content)
return err
}
// Delete ...
func (m ArticleModel) Delete(userID, id int64) (err error) {
_, err = m.One(userID, id)
if err != nil {
return errors.New("Article not found")
}
_, err = db.GetDB().Exec("DELETE FROM public.article WHERE id=$1", id)
return err
}