-
Notifications
You must be signed in to change notification settings - Fork 0
/
favorites.go
105 lines (75 loc) · 1.68 KB
/
favorites.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package models
import (
"errors"
"github.com/eirka/eirka-libs/db"
e "github.com/eirka/eirka-libs/errors"
)
// FavoritesModel holds the request input
type FavoritesModel struct {
UID uint
Image uint
}
// IsValid will check struct validity
func (m *FavoritesModel) IsValid() bool {
if m.UID == 0 || m.UID == 1 {
return false
}
if m.Image == 0 {
return false
}
return true
}
// ValidateInput will make sure all the parameters are valid
func (m *FavoritesModel) ValidateInput() (err error) {
if m.UID == 0 || m.UID == 1 {
return e.ErrInvalidParam
}
if m.Image == 0 {
return e.ErrInvalidParam
}
return
}
// Status will return info
func (m *FavoritesModel) Status() (err error) {
// check model validity
if !m.IsValid() {
return errors.New("FavoritesModel is not valid")
}
// Get Database handle
dbase, err := db.GetDb()
if err != nil {
return
}
var check bool
// Check if favorite is already there
err = dbase.QueryRow("SELECT count(1) FROM favorites WHERE image_id = ? AND user_id = ?", m.Image, m.UID).Scan(&check)
if err != nil {
return
}
// delete if it does
if check {
_, err = dbase.Exec("DELETE FROM favorites WHERE image_id = ? AND user_id = ?", m.Image, m.UID)
if err != nil {
return err
}
return e.ErrFavoriteRemoved
}
return
}
// Post will add the fav to the database
func (m *FavoritesModel) Post() (err error) {
// check model validity
if !m.IsValid() {
return errors.New("FavoritesModel is not valid")
}
// Get Database handle
dbase, err := db.GetDb()
if err != nil {
return
}
_, err = dbase.Exec("INSERT into favorites (image_id, user_id) VALUES (?,?)", m.Image, m.UID)
if err != nil {
return
}
return
}