-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpomodoros_db.go
66 lines (54 loc) · 1.65 KB
/
pomodoros_db.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
package tomeit
import (
"fmt"
"time"
)
type pomodoroDBInterface interface {
createPomodoro(userID, taskID int) (int, error)
getPomodoroByID(id int) (*Pomodoro, error)
getPomodorosByUser(user *User, options *getPomodorosOptions) ([]Pomodoro, error)
deletePomodoro(pomodoro *Pomodoro) error
}
func (db *DB) createPomodoro(userID, taskID int) (int, error) {
pomodoro := Pomodoro{
UserID: userID,
TaskID: taskID,
}
if err := db.Create(&pomodoro).Error; err != nil {
return 0, fmt.Errorf("db.Create failed: %w", err)
}
return pomodoro.ID, nil
}
func (db *DB) getPomodoroByID(id int) (*Pomodoro, error) {
var pomodoro Pomodoro
if err := db.Joins("Task").First(&pomodoro, id).Error; err != nil {
return nil, fmt.Errorf("db.First failed: %w", err)
}
return &pomodoro, nil
}
type getPomodorosOptions struct {
createdOnExists bool
createdOn time.Time
}
func (db *DB) getPomodorosByUser(user *User, options *getPomodorosOptions) ([]Pomodoro, error) {
q := db.Joins("Task").Where("pomodoros.user_id = ?", user.ID).Order("pomodoros.created_at").Limit(30)
if options != nil {
if options.createdOnExists {
y, m, d := options.createdOn.Date()
start := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
end := time.Date(y, m, d, 23, 59, 59, 0, time.UTC)
q = q.Where("pomodoros.created_at BETWEEN ? AND ?", start, end)
}
}
var pomodoros []Pomodoro
if err := q.Find(&pomodoros).Error; err != nil {
return nil, fmt.Errorf("q.Find failed: %w", err)
}
return pomodoros, nil
}
func (db *DB) deletePomodoro(pomodoro *Pomodoro) error {
if err := db.Delete(pomodoro).Error; err != nil {
return fmt.Errorf("db.Delete failed: %w", err)
}
return nil
}